How to combine various function files into a single nested function file?
Show older comments
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
Accepted Answer
More Answers (0)
Categories
Find more on Nonlinear Optimization in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!