First input argument must be a function handle.

1 view (last 30 days)
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

Accepted Answer

A. Sawas
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:
% your code
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));
% rest of your code
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
  2 Comments
Walter Roberson
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
A. Sawas on 14 Apr 2019
Thank you Walter Roberson for providing this comprehensive explanation. I am learning a lot from your comments.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!