フィルターのクリア

Not enough inputs with input parser

2 ビュー (過去 30 日間)
Ian Ammerman
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
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 Center および File ExchangeFunctions についてさらに検索

製品


リリース

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by