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.

6 次查看(过去 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 个)

标签

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by