我希望能够在 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/