%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? When 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?
The issue is that you try to assign to f(a)
where a=0
, so you mixed between a vector index and value, as well as use f
for two different purposes, one as the output of the function NC, and one for the value of fun(x), that's not a good idea.
Instead you can define the output in a separate variable:
fa=fun(a);
fb=fun(n);
f=(b-a)*(fa+fb)/2;
or just write: f=(b-a)*(fun(a)+fun(b))/2;