Cannot call or index into a temporary array error message

24 ビュー (過去 30 日間)
Aleem Andrew
Aleem Andrew 2020 年 4 月 21 日
編集済み: Liang Zhang 2023 年 7 月 16 日
I am trying to access the elements of a 1 by 2 variable that is defined by a function handle, p2r, but when I define a separate function handle p22r to do this I get the error message Cannot call or index into a temporary array. Is there a way I can access the elements of a 1 by 2 vector that has not yet been initialized?
r2p = @(x) [abs(x) rad2deg(angle(x))];
p2r = @(x) x(1)*exp(1i*deg2rad(x(2)));
pm = @(x,y) [x(1)*y(1) x(2)+y(2)];
pd = @(x,y) [x(1)/y(1) x(2)-y(2)];
p22r = @(x,y) p2r([x y])(:,1);

回答 (1 件)

Tarunbir Gambhir
Tarunbir Gambhir 2021 年 1 月 27 日
MATLAB does not support syntax which directly index the function call return value, like "p2r([x y])(:,1)". It is recommended that you use temporary intermediate variables for indexing in a function declaration, rather than using anonymous function for 'p22r'.
As an alternative, however, you could use workaround with some limitations on the result. For example, if you need to return a value at the particular index (1,1) of 'p2r([x y])', you can use getfield or subsref functions as
p22r = @(x,y) getfield(p2r([x y]),{1,1});
or
p22r = @(x,y) subsref(p2r([x y]), struct('type', '()', 'subs', {{1, 1}}));
  1 件のコメント
Liang Zhang
Liang Zhang 2023 年 7 月 16 日
編集済み: Liang Zhang 2023 年 7 月 16 日
This is just an unnecessary complication. I am wondering why this syntax is not supported while Octave and Scilab both support this syntax. The syntax could save life for some while.

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by