【问题标题】:Overloading indexing operators `()` and `{}` for custom classes in MATLAB为 MATLAB 中的自定义类重载索引运算符 `()` 和 `{}`
【发布时间】:2015-06-05 07:25:02
【问题描述】:

我希望能够在 MATLAB 中为我的班级重载索引运算符 (){}。特别是,我希望能够定义类方法...

% ...
classdef MyClass < handle

    % ... other class definition stuff...

    function returnVal = operator{}(indexRange)
        %....implementation here....
    end
    function returnVal = operator()(indexRange)
        %....implementation here....
    end
end

这样我就可以创建对象并执行...

x = MyClass();
returnedVals = x(:);
returnedCells = [x{:}];

% etc.

这在 MATLAB 中可行吗?我知道这在 C++ 和 python 中很容易(通过分别重载 operator []__get__ 运算符)。不过,Mathworks 网站本身并不太清楚如何做到这一点。

【问题讨论】:

    标签: matlab operator-overloading operator-keyword


    【解决方案1】:

    您需要在您的classdef 中使用overload the subsref and subsasgn 函数。 Mathworks 提供了一个full example 它的工作原理。请注意,如果您希望在您的类使用重载方法,您需要call it explicitly

    【讨论】:

      【解决方案2】:

      如果要实现subsrefsubsasgn,还需要实现:

      1. 尺寸
      2. 长度
      3. ndims
      4. 编号
      5. 结束

      您还应该考虑实施subsindex

      【讨论】:

      • 为什么是lengthlength 不只是做max(size(x))(或0 表示空),所以如果你已经完成size 应该没问题?还是length 实际上没有通过size
      • 嗯,不确定,我也一直实现length
      【解决方案3】:

      在 MATLAB 网站上,Class with Modified Index 指南展示了如何通过 subsref 方法重载 .(){} 运算符(更多最新文档 here)。

      这是他们为具有名为Data 的属性的类提供的 sn-p:

      function sref = subsref(obj,s)
         % obj(i) is equivalent to obj.Data(i)
         switch s(1).type
            case '.'
               sref = builtin('subsref',obj,s);
            case '()'
               if length(s) < 2
                  sref = builtin('subsref',obj.Data,s);
               else
                  sref = builtin('subsref',obj,s);
               end
            case '{}'
               error('MYDataClass:subsref',...
                  'Not a supported subscripted reference')
         end
      end
      

      在 MATLAB R2021b 及更高版本中,MathWorks 推荐了一种用于重载索引运算符的新方法,描述为 here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-05
        • 2021-09-17
        • 2015-03-08
        相关资源
        最近更新 更多