Create a local system of equations function from a set of anonymous functions

4 vues (au cours des 30 derniers jours)
Fernando
Fernando le 7 Juil 2023
Modifié(e) : Dyuman Joshi le 7 Juil 2023
Hello,
I have a set of N anounimous functions which are created using this code
equations = {'@(x1,x2)x1.^2+x2-6','@(x1,x2)-2.5.*x1+x2.^2-2'};%Set your equations
N = numel(equations);
f = cell(1,N);
for i = 1:N
f{i} = str2func(equations{i});
end
The thing is, in a later part of the program I would like to use fsolve to solve the system of equation and fsolve requires the a function in this equivalent form:
function F = root2d(x)
F(1) = x(1).^2+x(2)-6;
F(2) = -2.5.*x(1)+x(2).^2-2;
end
where root2d is the function inputted in fsolve. I was wondering if there was a way to create a function in this form from the upper form or a way to use fsolve using the upper form?
Kind regards

Réponses (2)

Paul
Paul le 7 Juil 2023
Modifié(e) : Paul le 7 Juil 2023
One approach:
equations = {'@(x1,x2)x1.^2+x2-6','@(x1,x2)-2.5.*x1+x2.^2-2'};%Set your equations
N = numel(equations);
f = cell(1,N);
for i = 1:N
f{i} = str2func(equations{i});
end
F = @(x) cellfun(@(func) func(x(1),x(2)),f)
F = function_handle with value:
@(x)cellfun(@(func)func(x(1),x(2)),f)
sol1 = fsolve(F,[2 2])
Equation solved. fsolve completed because the vector of function values is near zero as measured by the value of the function tolerance, and the problem appears regular as measured by the gradient.
sol1 = 1×2
1.8509 2.5743
F(sol1)
ans = 1×2
1.0e-13 * -0.0178 0.3109
[f{1}(sol1(1),sol1(2)) , f{2}(sol1(1),sol1(2))]
ans = 1×2
1.0e-13 * -0.0178 0.3109

Dyuman Joshi
Dyuman Joshi le 7 Juil 2023
Modifié(e) : Dyuman Joshi le 7 Juil 2023
Another approach (Note - requires Symbolic Toolbox)
equations = {'@(x1,x2) x1.^2+x2-6','@(x1,x2) -2.5.*x1+x2.^2-2'};%Set your equations
f = str2sym(equations);
z = matlabFunction(f,"File", "root2d", "Vars",{symvar(f)});
out = fsolve(z,[2 2])
Equation solved. fsolve completed because the vector of function values is near zero as measured by the value of the function tolerance, and the problem appears regular as measured by the gradient.
out = 1×2
1.8509 2.5743
z(out)
ans = 1×2
1.0e-13 * -0.0178 0.3109

Catégories

En savoir plus sur Mathematics dans Help Center et File Exchange

Produits


Version

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by