Let us first show expected behaviour:
classdef GoodDemo properties st; end methods function obj = GoodDemo() obj.st = struct('x', {1,2,3}); end endendgood = GoodDemo;disp(good.st(2).x); % --> 2
disp({good.st.x}); % --> [1] [2] [3]
However, when we overload subsref (just let it return the built-in output, nothing fancy) things break:
classdef BugDemo properties st; end methods function obj = BugDemo() obj.st = struct('x', {1,2,3}); end function varargout = subsref(obj, s) [varargout{1:nargout}] = builtin('subsref', obj, s); end endendbug = BugDemo;disp(bug.st(2).x); % --> 2disp({bug.st.x}); % --> [1]
The problem seems to be that in the overloaded subsref somehow `nargout == 1`. Anything I am doing wrong here?
I found a bit of a crazy workaround, and the most problematic thing about it is it is only supported from 2015b onwards. The workaroud is to also overload the `numArgumentsFromSubscript` with — big surprise — its built-in value:
classdef WeirdFixDemo properties st; end methods function obj = WeirdFixDemo() obj.st = struct('x', {1,2,3}); end function varargout = subsref(obj, s) [varargout{1:nargout}] = builtin('subsref', obj, s); end function n = numArgumentsFromSubscript(obj, s, ic) n = builtin('numArgumentsFromSubscript', obj, s, ic); end endendweird = WeirdFixDemo;disp(weird.st(2).x); % --> 2disp({weird.st.x}); % --> [1] [2] [3]
This works for Matlab 2015b+. Is there a way to get this working for earlier versions of Matlab? I tried setting `nargout` explicitly, but that has no effect at all.
Best Answer