classdef Dog
end
d=Dog()
; can size(d)
be controlled? Is there some property
to set or method
to overload?
Ultimately I have like d.data = [1, 2, 3]
and want length(d) == 3
. I'm aware I can make d.length()
. As an aside, is there a list of MATLAB "magic methods", i.e. functions that control interaction with classes, like subsref?
CodePudding user response:
In MATLAB, don't think of class method as similar to class methods in other languages. Really, what they are is overloaded versions of a function.
size(d)
is the same as d.size()
(which is the same as d.size
, parentheses are not needed to call a function), if d
is an object of a custom class and size
is overloaded for that class.
So, you can define function size
in the methods
section of your classdef
, to overload size
for your class. You can also create a size.m
file within a @Dog/
directory to accomplish the same thing.
For example, if you create a file @char/size.m
with a function definition inside, you will have overloaded size
for char arrays.
The above is true for any function. Some functions, when overloaded, can cause headaches. For example be careful when overloading numel
, as it could cause indexed assignment expressions to fail. size
is used by the whos
command to display variable information, as well as by the similar functionality in the GUI, so it is important to have it behave in the expected way.
The object behavior that you might want to change that is not obviously a function, relates to operators. Each operator is also defined by a function (including end
in indexing!). See the docs for a full list.