MATLAB: I’m stuck debugging a simple code. Maybe I’m making a mistake by assuming that there no difference between when MATLAB executes instructions in a script and when MATLAB executes instructions from the command window.

command windowfunction functionfunction handlepassing functionsscript

I run this simple script, entitled "proj3numan", written exactly as you see here:
f = @(h)(cos(h^2));
x = 0:(1/12):1 ;
trapezoid_integration(f,x)
I had previously saved "trapezoid_integration" as a function. Here is its simple code:
function [output] = trapezoid_integration(f, x)
n=max(size(x));
output = 0;
for i=1:(n-1)
output = output + (x(i+1)-x(i))*(f(x(i+1))+f(x(i)))/2;
end
end
I run the script, and I get this error:
Array indices must be positive integers or logical values.
Error in trapezoid_integration (line 7)
output = output + (x(i+1)-x(i))*(f(x(i+1))+f(x(i)))/2;
Error in proj3numan (line 8)
trapezoid_integration(f(x),x)
But, if I type the exact same thing that I typed in proj3numan, but into the command window instead, my code works perfectly. See for yourself:
>> f = @(h)(cos(h^2));
>> x = 0:(1/12):1 ;
>> trapezoid_integration(f,x)
ans =
0.9036
Maybe I'm making a mistake by assuming that there no difference between when MATLAB executes instructions in a script and when MATLAB executes instructions from the command window.

Best Answer

"I run this simple script, entitled "proj3numan", written exactly as you see here:"
Nope. That error message shows how you have actually called the function in the script:
trapezoid_integration(f(x),x)
^^^ you evaluate |f| already here!
This is different to what you called in the command window, and is the cause of that error: once you have evaluated f for the values of x like that it returns a numeric array, which inside the function you try to index into using values which are not positive integer. Thus the error.
Unfortunately this bug is easy to make with MATLAB because the syntax for function calls and linear/subscript indexing is identical.
Related Question