How to combine various function files into a single nested function file?
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Aaron Zambiasi
le 12 Avr 2020
Commenté : Ameer Hamza
le 13 Avr 2020
Here are four function files that utilize Newton's method to solve a system of nonlinear equations. Separately, these functions solve for unknowns x1 and x2 just fine. However, I am required to combine these function files together, but I simply don't know how. Either nested functions or one simplified function file are required.
function x = NewtonSol
x0 = [2;3];
x = NewtonMethod(@function_def,@Jacobian_def,100,10^-5,x0);
%using built in function
xsol = fsolve(@function_def,x0);
end
function x = NewtonMethod(funcF,JacobianF,max_iter,epsilon,x0)
f = funcF;
J = JacobianF;
x = x0;
iter = 1;
while iter < max_iter
y = J(x)\(-f(x));
x = x + y;
if norm(y, 2) < epsilon
break;
end
iter = iter + 1;
end
if iter >= max_iter + 1;
fprintf('No solution found');
end
function A = Jacobian_def(x)
x1 = x(1);
x2 = x(2);
A = zeros(2,2);
A(1,1) = 2*(x1); %df1x1
A(1,2) = 2*(x2); %df1x2
A(2,1) = (16/3)*(x1)^(-1/3); %df2x1
A(2,2) = (1/3)*(x2)^(-2/3); %df2x2
end
function y = function_def(x)
x1 = x(1);
x2 = x(2);
y = zeros(2,1);
y(1) = ((x1)^2) + ((x2)^2) - 17; %f1(x1,x2)
y(2) = (8*(x1)^(2/3)) + (x2)^(1/3) - 4; %f2(x1,x2)
end
0 commentaires
Réponse acceptée
Ameer Hamza
le 12 Avr 2020
Modifié(e) : Ameer Hamza
le 12 Avr 2020
See Nested functions: https://www.mathworks.com/help/matlab/matlab_prog/nested-functions.html
This can be saved in one file called NewtonSol.m
function x = NewtonSol
x0 = [2;3];
x = NewtonMethod(@function_def,@Jacobian_def,100,10^-5,x0);
%using built in function
xsol = fsolve(@function_def,x0);
function x = NewtonMethod(funcF,JacobianF,max_iter,epsilon,x0)
f = funcF;
J = JacobianF;
x = x0;
iter = 1;
while iter < max_iter
y = J(x)\(-f(x));
x = x + y;
if norm(y, 2) < epsilon
break;
end
iter = iter + 1;
end
if iter >= max_iter + 1;
fprintf('No solution found');
end
end
function A = Jacobian_def(x)
x1 = x(1);
x2 = x(2);
A = zeros(2,2);
A(1,1) = 2*(x1); %df1x1
A(1,2) = 2*(x2); %df1x2
A(2,1) = (16/3)*(x1)^(-1/3); %df2x1
A(2,2) = (1/3)*(x2)^(-2/3); %df2x2
end
function y = function_def(x)
x1 = x(1);
x2 = x(2);
y = zeros(2,1);
y(1) = ((x1)^2) + ((x2)^2) - 17; %f1(x1,x2)
y(2) = (8*(x1)^(2/3)) + (x2)^(1/3) - 4; %f2(x1,x2)
end
end
2 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Calculus dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!