# Not enough inputs with input parser

조회 수: 1 (최근 30일)
Ian Ammerman . 2023년 9월 21일
편집: Chunru . 2023년 9월 22일
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 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

댓글을 달려면 로그인하십시오.

### 카테고리

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