Does the access method of a dependent property get called twice when the property is indexed into?

1 回表示 (過去 30 日間)
I have a class with a dependent property z. The method get.z(obj) returns a vector. This:
y = myObj.z(end);
appears to call get.z twice! The profiler shows 2 calls from the parent function and the run time is twice the expected run time. On the other hand:
x = myObj.z;
y = x(end);
calls get.z once and cuts down run time by half. Is this the intended behavior?
  1 件のコメント
Walter Roberson
Walter Roberson 2016 年 10 月 13 日
I speculate that one of the two is due to the "end", as it would need to find the size . This is just speculation on my part, though.

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

採用された回答

Naor Movshovitz
Naor Movshovitz 2016 年 10 月 13 日
Confirmed Walter's comment. Indeed the culprit is the keyword end. Here is minimal working example.
classdef Untitled
properties (Dependent)
x;
end
methods
function val = get.x(~)
fprintf('called\n')
val = [1,2,3];
end
end
end
>> obj = Untitled;
>> obj.x(2);
called
ans =
2
>> obj.x(end)
called
called
ans =
3
This behavior is mostly benign but occasionally troublesome, and easy to fix. I think this is a case for an m-lint message at least.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by