Short-circuit logic and dynamic structure referencing: Why does this not work?

1 回表示 (過去 30 日間)
Chris
Chris 2015 年 10 月 25 日
コメント済み: Chris 2015 年 10 月 26 日
This behavior seems rather inconsistent, especially since by my understanding of short-circuit logic the A.(x) bit should not be evaluated if isfield(A,x) is false. Can someone help me understand this behavior? Thank you!
>> A = struct('apple',1, 'orange',1);
>> x = 'apple';
>> isfield(A,x) && A.(x)
ans =
1
>> x = 'banana';
>> isfield(A,x) && A.(x)
ans =
0
>> isfield(A,x) & A.(x)
Reference to non-existent field 'banana'.
>> for x = {'apple','banana'}
.. isfield(A,x) && A.(x)
.. end
Argument to dynamic structure reference must evaluate to a valid field name.

採用された回答

Walter Roberson
Walter Roberson 2015 年 10 月 25 日
Nothing to do with short circuit logic.
for x = {'apple','banana'}
does not assign x = 'apple' and then x = 'banana': instead it assigns x = {'apple'} and then x = {'banana'}
  1 件のコメント
Chris
Chris 2015 年 10 月 26 日
Perfect, that's exactly the sort of detail I would have overlooked for way too long. Thank you.

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

その他の回答 (0 件)

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by