MATLAB: How to get a class property to be overridden and handled as a variable

classobject-orientedoopoverload

Some of the Matlab classes have a great features, e.g. TABLE, by letting the class be called with a property that is really a variable inside the class.
For example:
somedata = {'a','b','c'}
T = table (somedata)
And you can then access the row of "a" by calling
T.a
and you can even call it with "modifiers", e.g.
T.a(end-1:end)
to get the last two rows
How can this be replicated in my own class definition / how does a class "capture" that this is not a real method/property, but to be treated as a variable? And how is the "end-1:end" command captured in this case so it can be used in the class?

Best Answer

  • There are various ways to customise properties such as dynamic properties.
    However, what you're looking at here with table has nothing to do with customised or overriden properties. The T.xxx T{xxx, yyy} and T(xxx, yyy) syntax override the default indexing (subsref) and default assignment (subsasgn) methods. As for end, it is the end method that is overriden.
    For example the line
    T{end-1:end, 'a'}
    is actually
    • two calls to end(T, 1)
    • a call to numArgumentsFromSubscript
    • finally a call to subsref(t, struct('type', '{}','subs', {[calculatedindex calculatedindex], 'a'})
    The line
    T.a(end-1:end)
    is actually a call to
    subsref(t, struct('type', '.', 'subs', {'a'});
    followed by a plain matrix indexing.
    You can do the same for your own class. It's all explained under Obejct Indexing. However, be aware that it's a lot of work to get right. You can actually see how it's implemented for tables. It's all in m files. The simples way is to use the debugger to step through a line that index a table. Or you can find the implementation of the overriding methods in
    fullfile(matlabroot, 'toolbox\matlab\datatypes\@tabular')