matlab - 为 MATLAB 中的自定义类重载索引运算符 `()` 和 `{}`

标签 matlab operator-overloading operator-keyword

我希望能够在 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 网站本身并不太清楚如何执行此操作。

最佳答案

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

关于matlab - 为 MATLAB 中的自定义类重载索引运算符 `()` 和 `{}`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29377391/

相关文章:

c++ - C++中operator[]()一定要是成员函数吗?

c++ - 为类重载 = 运算符

c++ - 试图减少几乎但不完全是整数类的速度开销

C++ 模板与 operator< 不匹配

matlab - 如何让 fminsearch 只搜索整数?

matlab - 如何将不均匀矩阵组合成单个矩阵?

c++ - 运算符 [] 重载 C++

c++ - 排序中的 < 运算符断言无效

matlab - 使用 matlab 高效可视化大量点。

matlab - 比较两个表中的字符串matlab