Not Enough Input Arguments: Newtons Method/Jacobian Matrix

11 views (last 30 days)
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];
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);
while norm(xnew-xold)>tol
gradfxk = gradfun(xnew);
fxk = fun(xnew);
fxk = fxk(:); % this will force fxk to be a column vector
if a~=n || b~=1
error('function has wrong dimension, expecting %d x 1, but got %d x %d',n, a, b)
if a~=n || b~=n
error('gradient has wrong dimension, expecting %d x %d, but got %d x %d',n, n, a, b)
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])
if (numits>=100)
root = xnew;
fprintf('current step:\n')
error('no convergence after %d iterations', numits);
root = xnew;
  1 Comment
Jan on 9 Mar 2023
Edited: Jan on 9 Mar 2023
Please post a copy of the complete message instead of paraphrasing some parts of it. Which line is "in the "gradfun" line"?
Please use the tools to format code. This improves the readability of the code.

Sign in to comment.

Answers (1)

Jan on 9 Mar 2023
Edited: Jan on 9 Mar 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)];


Find more on Get Started with Symbolic Math Toolbox 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!

Translated by