Azzera filtri
Azzera filtri

Overloading end indexing for user defined classes

4 visualizzazioni (ultimi 30 giorni)
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 Commenti
Rik
Rik il 21 Feb 2022
I would assume you can leave end alone and only overload subsref. Did you try anything yet?
Leon
Leon il 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

Accedi per commentare.

Risposta accettata

Leon
Leon il 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

Più risposte (0)

Categorie

Scopri di più su Data Type Identification in Help Center e File Exchange

Prodotti


Release

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by