Overloading subsref and calling the builtin from within causes the class to only return the first value when called on a nested vector of objects.

8 ビュー (過去 30 日間)
To explain this problem, I have made a minimal example. I created two classes, one with an overloaded subsref and one without.
classdef NonSubsrefExample
properties
Property
end
methods
function obj = NonSubsrefExample(prop)
obj.Property = prop;
end
end
end
classdef SubsrefExample
properties
Property
PropertyOverloaded
end
methods
function obj = SubsrefExample(prop)
obj.Property = prop;
obj.PropertyOverloaded = prop;
end
function varargout = subsref(obj, S)
if S(1).subs == "PropertyOverloaded"
varargout = {"Dot"};
return
end
[varargout{1:nargout}] = builtin('subsref', obj, S);
end
end
end
Now if we create a nested vector of these objects:
subsrefExample = SubsrefExample([SubsrefExample(1), SubsrefExample(2)]);
nonSubsrefExample = NonSubsrefExample([NonSubsrefExample(1), NonSubsrefExample(2)]);
We can now operate on these and see what happens
[subsrefExample.Property.Property] % Returns 1
[nonSubsrefExample.Property.Property] % Returns [1, 2] as expected

採用された回答

James Lebak
James Lebak 2022 年 11 月 4 日
To get the behavior you want, your class needs to overload numArgumentsFromSubscript. One example implementation of this method would look like the following. The rest of your class would remain the same.
function n = numArgumentsFromSubscript(obj, S, ctx)
n = builtin('numArgumentsFromSubscript', obj, S, ctx);
end
The point of numArgumentsFromSubscript is to tell MATLAB how many outputs the particular instance of your class returns when indexed in a certain way.
When I add this method to your class, the new class works the way you expect:
>> enhancedSubsrefExample = EnhancedSubsrefExample([EnhancedSubsrefExample(1), EnhancedSubsrefExample(2)]);
>> [enhancedSubsrefExample.Property.Property] % Returns [1, 2]
It's also worth nothing that in recent releases, you can use modular indexing mixins such as RedefinesParen and RedefinesDot in place of overloading subsref and subsasgn. If you are able to use modular indexing, it will generally result in better performance when your class overloads indexing.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeClass Introspection and Metadata についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by