# Not enough inputs with input parser

1 view (last 30 days)
Ian Ammerman on 21 Sep 2023
Edited: Chunru on 22 Sep 2023
I am trying to use input parser to add optional inputs to my own function, newtonsMethod:
function x = newtonsMethod(func,guess)
% newtonsMethod(func,guess) computes the zero of the function func using Newton's method
% beginning at the x = guess. If multiple solutions are known to be present near guess,
%
% newtonsMethod(func,guess,tol) allows the user to specify the tolerance for
% convergence
%
% newtonsMethod(func,guess,tol,dx) specifies the increment dx used for
% computing the numerical derivative of func at a point.
p = inputParser;
parse(p);
%% ---------------------------------------------------------------------- %%
maxiter = 10^7;
iter = 0;
x = guess;
while abs(func(x)) > tol && iter < maxiter
fpx = (func(x+dx)-fx)/dx;
x = x - fx/fpx;
end
I am then calling this function using a driver file:
F = @(x) x.^2.*sin(x)-0.2.*x.^3+3.*x.^2+x-4-0.005.*x.^4;
nx = newtonsMethod(F,6.5)
But I am getting the error "Not enough input arguments.". Adding tol and dx to the function definition yields the same error, as does adding varargin to the function definition and adding it to the parse command as parse(p,varargin{:}). My code seems to follow the Matlab documentation example directly but I can't seem to get it to run.

Chunru on 22 Sep 2023
Edited: Chunru on 22 Sep 2023
F = @(x) x.^2.*sin(x)-0.2.*x.^3+3.*x.^2+x-4-0.005.*x.^4;
nx = newtonsMethod(F,6.5)
nx = -1.5544
function x = newtonsMethod(func,guess,tol,dx)
arguments
func
guess (1, 1) double
tol (1, 1) double = 1e-6;
dx (1, 1) double = 1e-4;
end
%% ---------------------------------------------------------------------- %%
maxiter = 10^5;
iter = 0;
x = guess;
fx = func(x);
while abs(fx) > tol && iter < maxiter
fpx = (func(x+dx)-fx)/dx;
x = x - fx/fpx;
fx = func(x);
iter = iter+1;
end
end

### Categories

Find more on Functions in Help Center and File Exchange

R2023b

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!