"Array Indices Must Be Positive Integers or Logical Values"
Problem Details and Clues %For This Problem Write a Script File Called Nc. M That Implements %The Newton-Cotes Method of Integration for an Arbitrary Function...
%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?
2 Answers
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;
The problem lies in the assignments to f(a) and f(b).
The syntax f(x) has three interpretations in MATLAB that are dependent on the type of f:
- indexing the array
fusing the strictly positive integer index (or logical index)x - evaluation of the function handle
fusing the value of the variablex - manipulation, in some manner, of the symbolic function
f(x)using the symbolic variablex.
Due to MATLAB's dynamic typing and defaulting to double arrays, MATLAB is interpreting the assignments to f(a) and f(b) as the item (1): MATLAB is taking f to be a double array and is expecting a and b to be valid indexes into the array.
Per your intent then, a simple assignment to variable symbols without the parentheses (e.g., fa and fb) should solve your problem.