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 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Damien Watson
am 10 Okt. 2022
Beantwortet: James Lebak
am 4 Nov. 2022
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
0 Kommentare
Akzeptierte Antwort
James Lebak
am 4 Nov. 2022
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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Common Weakness Enumeration (CWE) finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!