简体   繁体   中英

MATLAB: Not enough input arguments error given

I am given the error

Not enough input arguments.

Error in fun (line 2) f = cos(2*x)./exp(x);

When trying to run my code with the command

simp(fun, 0, 2*pi, 120)

for my code

function I = simp(fun, a,b,n)

%Standard simpson's rule 
tol = 0.0001;

h = (b-a)/(2*n); % The subinterval spacing
x = a:h:b; % The partition points
y = fun(x); % The function values at those points
i = 0:2*n; % Makes a list from 0 to 2*n

coeffs = 3+(-1).^(i+1); % Makes a list of 2s and 4s to use in the Simpson's Rule
coeffs(1) = 1; coeffs(end)=1;

SR = h/3 * sum(coeffs .* y); % This is the Simpson's Rule
disp(SR);

function f = fun(x)
f = cos(2*x)./exp(x);
end

The error is telling me that I did not provide enough input arguments, but I see that I give the function (fun), 'a', 'b', and 'n' values. So why am I getting this error?

You need to pass the function handle with @ :

simp(@fun, 0, 2*pi, 120)

You can also use:

simp(@(x) cos(2*x)./exp(x), 0, 2*pi, 120)

When you use only fun , Matlab think you try to call the function with no parameter. @fun is the actual function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM