Effacer les filtres
Effacer les filtres

Overloading end indexing for user defined classes

4 vues (au cours des 30 derniers jours)
Leon
Leon le 21 Fév 2022
Réponse apportée : Leon le 22 Fév 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 commentaires
Rik
Rik le 21 Fév 2022
I would assume you can leave end alone and only overload subsref. Did you try anything yet?
Leon
Leon le 21 Fév 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

Connectez-vous pour commenter.

Réponse acceptée

Leon
Leon le 22 Fév 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

Plus de réponses (0)

Catégories

En savoir plus sur Data Type Identification dans Help Center et File Exchange

Produits


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by