Overloading end indexing for user defined classes

4 次查看(过去 30 天)
When overloading parenthesis indexing for user defined classes, is there a way to overload 'end' indexing such that it behaves differently for '()' and '{}' indexing. For example, I would like that 'myClass(end)' returns the last object in the object array, whereas 'myClass{end}' returns the last element of a property defined in myClass. The solution should also be valid for slicing, e.g. 'myClass(100:end)'.
Could this be implemented in the overloaded 'subsref()' method or possibly in the overloaded 'end()' method?
  2 个评论
Rik
Rik 2022-2-21
I would assume you can leave end alone and only overload subsref. Did you try anything yet?
Leon
Leon 2022-2-21
Yes, I overloaded end method to act on object property, but this ruined object array behaviour:
function out = end(obj, k, ~)
% Overload object indexing with 'end()'
out = size(obj.trcArr, k);
end
And the shortened version of overloaded indexing method:
function varargout = subsref(obj, s)
% Overload parenthesis indexing.
% Structure 's' defines indexing where only '{}' is changed.
% Indexing using '()' and '.' is kept as default.
switch s(1).type
case '.'
% Keep built-in functionality for '.'
[varargout{1:nargout}] = builtin('subsref', obj, s);
case '()'
% Keep built-in functionality for '()'
[varargout{1:nargout}] = builtin('subsref', obj, s);
case '{}'
% Implement obj{index} functionality
% My code is here
% Could I call different 'end()' implementation for '{}' indexing from here
otherwise
error('Indexing expression invalid.')
end
end

请先登录,再进行评论。

采纳的回答

Leon
Leon 2022-2-22
I have manged to resolve this by omitting subsref() method and inheriting the new indexing class 'matlab.mixin.indexing.RedefinesBrace' that was introduced in 2021b. This one gives you more control over indexing and is easier to implement.
https://uk.mathworks.com/help/matlab/ref/matlab.mixin.indexing.redefinesbrace-class.html

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Type Identification 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by