フィルターのクリア

Overloading end indexing for user defined classes

4 ビュー (過去 30 日間)
Leon
Leon 2022 年 2 月 21 日
回答済み: Leon 2022 年 2 月 22 日
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 Center および File ExchangeData Type Identification についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by