First input argument must be a function handle.

1 回表示 (過去 30 日間)
mohamed elkasemy
mohamed elkasemy 2019 年 4 月 14 日
コメント済み: A. Sawas 2019 年 4 月 14 日
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
A. Sawas 2019 年 4 月 14 日
編集済み: A. Sawas 2019 年 4 月 14 日
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 件のコメント
Walter Roberson
Walter Roberson 2019 年 4 月 14 日
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 2019 年 4 月 14 日
Thank you Walter Roberson for providing this comprehensive explanation. I am learning a lot from your comments.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by