How to combine various function files into a single nested function file?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Aaron Zambiasi
am 12 Apr. 2020
Kommentiert: Ameer Hamza
am 13 Apr. 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 Kommentare
Akzeptierte Antwort
Ameer Hamza
am 12 Apr. 2020
Bearbeitet: Ameer Hamza
am 12 Apr. 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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Calculus finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!