I would like to be able to overload the indexing operators ()
and {}
for my class in MATLAB. In particular, I want to be able to define the class methods like...
% ...
classdef MyClass < handle
% ... other class definition stuff...
function returnVal = operator{}(indexRange)
%....implementation here....
end
function returnVal = operator()(indexRange)
%....implementation here....
end
end
so that I can create objects and do...
x = MyClass();
returnedVals = x(:);
returnedCells = [x{:}];
% etc.
Is this possible in MATLAB? I know this is easy in C++ and python ( by overloading operator []
and __get__
operators respectively ). The Mathworks site itself was not too clear on how to do this though.
You need to overload the subsref
and subsasgn
functions within your classdef
. The Mathworks provides a full example of how it works. And note that if you wish to use your overloaded method within your class, you need to call it explicitly.