I would like to overload only one type of subsref calls (type '()) for a particular class and leave any other Matlab calls built into subsref - in particular, I want Matlab to handle access to properties / methods via'. ' a type. But it seems that the Matlab built-in function does not work when subsref is overloaded in the class.
Consider this class:
classdef TestBuiltIn properties testprop = 'This is the built in method'; end methods function v = subsref(this, s) disp('This is the overloaded method'); end end end
To use the overloaded subsref method, I do the following:
t = TestBuiltIn; t.testprop >> This is the overloaded method
This is as expected. But now I want to call Matlab, which is built into the subsref method. To make sure that I'm doing it right, first try a similar call in the structure:
x.testprop = 'Accessed correctly'; s.type = '.'; s.subs = 'testprop'; builtin('subsref', x, s) >> Accessed correctly
As expected. But, when I try to use the same method on TestBuiltIn:
builtin('subsref', t, s) >> This is the overloaded method
... Matlab calls the overloaded method, not the built-in method. Why does Matlab call an overloaded method when I asked it to call an inline method?
UPDATE: In response to the @Andrew Janke answer, this solution almost works, but not quite. Consider this class:
classdef TestIndexing properties prop1 child end methods function this = TestIndexing(n) if nargin==0 n = 1; end this.prop1 = n; if n<2 this.child = TestIndexing(n+1); else this.child = ['child on instance ' num2str(n)]; end end function v = subsref(this, s) if strcmp(s(1).type, '()') v = 'overloaded method'; else v = builtin('subsref', this, s); end end end end
It all works:
t = TestIndexing; t(1) >> overloaded method t.prop1 >> 1 t.child >> [TestIndexing instance] t.child.prop1 >> 2
But this does not work; it uses the built-in subsref for the child, not the overloaded subsref:
t.child(1) >> [TestIndexing instance]
Note that the above behavior is incompatible with both of these behavior (as expected):
tc = t.child; tc(1) >> overloaded method x.child = t.child; x.child(1) >> overloaded method