"Array indices must be positive integers or logical values". Please help

1 次查看(过去 30 天)
%For this problem write a script file called NC.m that implements
%the Newton-Cotes method of integration for an arbitrary function f(x). It
%should take as inputs the function and the limits of integration [a: b] and
%output the value of the definite integral. Specifically, you should use the
%Trapezoid rule as presented in Equation (11.73)
function [f]= NC(a,b,fun) %newton-cotes
%a and b are limits of intergration
%setting it up
f(a)= fun(a); %y value for lower limit
f(b)= fun(b); %y value for upper limit
%the actual function
f= (b-a)*(f(a)+f(b))/2;
end
What am i doing wrong? Whe I type, [f]= NC(-3,0,fun) and set fun= @(x)normpdf(x) . it keeps on returning "Array indices must be positive integers or logical values". Can someone shine some light on this?

采纳的回答

Steven Lord
Steven Lord 2020-10-2
By the way you called your function:
[f]= NC(-3,0,fun)
you're trying to assign to the -3rd element of f with the code:
f(a)= fun(a); %y value for lower limit
and to the 0th element of f with:
f(b)= fun(b); %y value for upper limit
Neither of those are valid in MATLAB. The first element of an array in MATLAB is element 1.
Try just assigning to fa and fb instead and using those variables later in your code.

更多回答(0 个)

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by