Not enough inputs with input parser

2 次查看(过去 30 天)
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,
% consider using findZero instead.
%
% 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;
addRequired(p,'func')
addRequired(p,'guess')
addOptional(p,'tol',10^-6)
addOptional(p,'dx',10^-4)
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
Chunru 2023-9-22
编辑:Chunru 2023-9-22
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Functions 的更多信息

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by