Not Enough Input Arguments: Newtons Method/Jacobian Matrix
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hey all, I am getting a "not enough input arguments" in the following code in the "gradfun" line, which is the jacobian matrix of the three functions listed in the vector "fun". Can anyone help with this?
tol = 10^-9;
x0 = [-1 1 1];
x = x0(1);
y = x0(2);
z = x0(3);
fun = @(x,y,z) [x^2-y-sin(z)+1, x+1+sin(10*y)-y, (1-x)*z-y];
gradfun = @(x,y,z) [2*x, -1, -cos(z); 1, 10*cos(10*y)-1, 0;-z,-1,1-x];
newton(fun,gradfun,x0,tol)
The newton function, which i from a textbook of mine, is as follows:
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);
%data_x=[xnew(1)];
%data_y=[xnew(2)];
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;
xnew = xold - (gradfxk)^{-1} * fxk, but implement as a linear solve
xnew = xold - gradfxk \ fxk;
numits = numits+1;
plot(xnew(1), xnew(2),'-o','MarkerEdgeColor','black');
%xlim([-5 5])
%ylim([-80 10])
pause(0.1)
if (numits>=100)
root = xnew;
fprintf('current step:\n')
disp(xnew)
error('no convergence after %d iterations', numits);
end
end
root = xnew;
root
end
1 comentario
Respuestas (1)
Jan
el 9 de Mzo. de 2023
Editada: Jan
el 9 de Mzo. de 2023
You define gradfun with 3 inputs:
gradfun = @(x,y,z) ...
In the code you call it with 1 input:
gradfxk = gradfun(xnew);
The same happens in the next line with fun():
fxk = fun(xnew);
Either call them as
gradfxk = gradfun(xnew(1), xnew(2), xnew(3));
fxk = fun(xnew(1), xnew(2), xnew(3));
Or define the functions as:
fun = @(x) [x(1)^2-x(2)-sin(x(3))+1, x(1)+1+sin(10*x(2))-x(2), (1-x(1))*x(3)-x(2)];
gradfun = @(x) [2*x(1), -1, -cos(x(3)); 1, 10*cos(10*x(2))-1, 0;-x(3),-1,1-x(1)];
0 comentarios
Ver también
Categorías
Más información sobre Software Development Tools en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!