gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:22:01 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com