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 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Damien Watson
el 10 de Oct. de 2022
Respondida: James Lebak
el 4 de Nov. de 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 comentarios
Respuesta aceptada
James Lebak
el 4 de Nov. de 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 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Common Weakness Enumeration (CWE) en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!