# First input argument must be a function handle.

3 views (last 30 days)
mohamed elkasemy on 14 Apr 2019
Commented: A. Sawas on 14 Apr 2019
clc;
clear all;
close all;
X0 = linspace(0.1,0.99,50);
for i = 1:length(X0)
Ts = 1;
T(i) = Ts*acos((Ts-X0(i))/Ts);
v(i) = sqrt(1-((Ts-X0(i))/Ts).^2);
dE(i) = @(t) 0.5*(-((X0(i)-Ts)./Ts).*sin(t./Ts)+v(i).*cos(t./Ts)+Ts).^2;
E(i) = integral(dE(i),0,T(i))
end

A. Sawas on 14 Apr 2019
Edited: A. Sawas on 14 Apr 2019
You cannot use nonscalar arrays of function handles .. use cell arrays instead:
dE{i} = @(t) 0.5*(-((X0(i)-Ts)./Ts).*sin(t./Ts)+v(i).*cos(t./Ts)+Ts).^2;
E(i) = integral(dE{i},0,T(i));
You may also need to consider preallocating the vectors T, v, dE, and E to enhance the runtime speed. One simple way to do that is by using inverse for loop:
for i = length(X0):-1:1

Walter Roberson on 14 Apr 2019
Expanding:
You can store a single function handle in a regular variable,
dE = @(t) etc
but you cannot store more than one function handle in a regular variable,
dE(2) = @(t) etc %not permitted
It is an oddity of MATLAB syntax that because dE(1) is considered a scalar location, it is considered to be valid to write
dE(1) = @(t) etc
and this does not trigger the error about trying to store multiple function handles in an array.
But then on the next line, you have
integral(dE(i), 0, T(i))
and when i = 1, then you thought you were referring to the first function handle, but because storing to dE(1) is the same as storing to dE by itself for this purpose, dE is just a plain function handle, and dE(i) has accidentally invoked the function handle with (i) as the argument. That calculates something, a double probably, and returns it, and that double gets passed to integral() in the first parameter, and then integral() looks at the first parameter and says, "Whoa! Hold on! That's not a function handle, that's a double!" . And that is why the error that comes up is from integral() rather than from storing to dE(1)
A. Sawas on 14 Apr 2019
Thank you Walter Roberson for providing this comprehensive explanation. I am learning a lot from your comments.