필터 지우기
필터 지우기

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개)

카테고리

Help CenterFile Exchange에서 Customize Object Indexing에 대해 자세히 알아보기

태그

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by