. Advertisement .
..3..
. Advertisement .
..4..
How to check – array indices must be positive integers or logical values.? I have the sample detail:
%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
While I run it, I found the warning message:
Array indices must be positive integers or logical values
That is my question and it is urgent. I searched for the solution on some websites, but I didn’t get it. I may miss any line or other changes. I appreciate your assistance!
The cause: You try to assign
f(a)
toa=0
wherea=0
. Therefore, this creates a problem because you can usef
for both outputs of the function NC and for fun(x) purposes.Solution: You can instead define the output as a separate variable.
Or, just write
f=(b-a)*(fun(a)+fun(b))/2;
The problem is in the assignment to
f(a)
orf(b)
.Three interpretations of the syntax
f(x)
in MATLAB are available depending on thef
type:f
with strictly positive integer index or logical indexx
f
usingx
variable valuex
allows manipulation of the symbol functionf(x)
in some way.MATLAB’s dynamic typing, which defaults to double arrays in MATLAB, is causing MATLAB to interpret the
f(a)
andf(b)
assignments as items (1). MATLAB considersf
a double array, and expectsa
to be valid indexes to the array.If you have the right intent, then a simple assignment of variable symbols should be sufficient to solve your problem.