How do I make this non-linear system into a matrix using function handles?
2 次查看(过去 30 天)
显示 更早的评论
I am trying to find the roots of a non-linear system by using the Newton function my professor gave us. I believe the error I am receiving mean I need to make my function vector into a matrix (using cell arrays? not entire sure what that is). But I am having trouble separating the 3 equations into a 3x3 matrix.
Professor's Newton method code:
function [root,numits] = newton(fun,gradfun,x0,tol)
% Solve fun(x)=0 using Newton's method given the function and its gradient
% gradfun starting from the initial guess x0.
x0 = x0(:); % this will force x0 to be a column vector
xold = x0+1; % this needs to be ~= x0 so that we enter the while loop
xnew = x0;
numits = 0;
n = length(x0);
while norm(xnew-xold)>tol
gradfxk = gradfun(xnew);
fxk = fun(xnew);
fxk = fxk(:); % this will force fxk to be a column vector
[a,b]=size(fxk);
if a~=n || b~=1
error('function has wrong dimension, expecting %d x 1, but got %d x %d',n , a, b)
end
[a,b]=size(gradfxk);
if a~=n || b~=n
error('gradient has wrong dimension, expecting %d x %d, but got %d x %d', n, n, a, b)
end
xold = xnew;
% x_k+1 = x_k - (grad f(xk))^{-1} * f(xk), but implement as a linear solve
xnew = xnew - gradfxk \ fxk;
numits = numits+1;
if (numits>=100)
root = xnew;
fprintf('current step:\n')
disp(xnew)
error('no convergence after %d iterations', numits);
end
end
root = xnew;
end
Linear system trying to solve: 0=x^2-y-sin(z)+1 0=x+20+sin(10y)-y 0=(1-x)z-2
My code when trying to use Newton function:
x0=[1,1,1];
f1 = @(x) x(1)^2-x(2)-sin(x(3))+1;
f2 = @(x) x(1)+sin(10*x(2))-x(2)+20;
f3 = @(x) (1-x(1))*x(2)-2;
fun={f1;f2;f3};
gf1 = @(x) 2*x(1)-1-cos(x(3));
gf2 = @(x) 1+10*cos(10*x(2))-1;
gf3 = @(x) -x(3)+1-x(1);
gradfun={gf1;gf2;gf3};
[root,numits] = newton(fun,gradfun,x0,1e-14);
Error in command window:
Error using newton (line 24)
gradient has wrong dimension, expecting 3 x 3, but got 3 x 1
Error in hw5q3 (line 21)
[root,numits] = newton(fun,gradfun,x0,1e-14)
0 个评论
回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Symbolic Math Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!