Azzera filtri
Azzera filtri

Not enough inputs with input parser

2 visualizzazioni (ultimi 30 giorni)
Ian Ammerman
Ian Ammerman il 21 Set 2023
Modificato: Chunru il 22 Set 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,
% 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.

Risposta accettata

Chunru
Chunru il 22 Set 2023
Modificato: Chunru il 22 Set 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

Più risposte (0)

Categorie

Scopri di più su Functions in Help Center e File Exchange

Prodotti


Release

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by