Filter löschen
Filter löschen

Overloading end indexing for user defined classes

4 Ansichten (letzte 30 Tage)
Leon
Leon am 21 Feb. 2022
Beantwortet: Leon am 22 Feb. 2022
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 Kommentare
Rik
Rik am 21 Feb. 2022
I would assume you can leave end alone and only overload subsref. Did you try anything yet?
Leon
Leon am 21 Feb. 2022
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

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Leon
Leon am 22 Feb. 2022
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

Weitere Antworten (0)

Kategorien

Mehr zu Data Type Identification finden Sie in Help Center und File Exchange

Produkte


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by