Why does MATLAB throw a "too many output arguments" error when I overload subsref (subscripted reference)?

Viewed 8639

As a toy example, I have a class that simply wraps a vector or matrix in an object and includes a timestamp of when it was created. I'm trying to overload subsref so that

  1. () referencing works exactly as it does with the standard vector and matrix types
  2. {} referencing works in exactly the same way as () referencing (nothing to do with cells in other words)
  3. . referencing allows me to access the private properties of the object and other fields that aren't technically properties.

Code:

classdef TimeStampValue

    properties (Access = private)
        time;
        values;
    end

    methods
        %% Constructor
        function x = TimeStampValue(values)
            x.time = now();
            x.values = values;
        end

        %% Subscripted reference
        function x = subsref(B, S)
            switch S.type
                case '()'
                    v = builtin('subsref', B.values, S);
                    x = TimeStampValue(v);
                case '{}'
                    S.type = '()';
                    v = builtin('subsref', B.values, S);
                    x = TimeStampValue(v);
                case '.'
                    switch S.subs
                        case 'time'
                            x = B.time;
                        case 'values'
                            x = B.values;
                        case 'datestr'
                            x = datestr(B.time);
                    end
            end
        end

        function disp(x)
            fprintf('\t%d\n', x.time)
            disp(x.values)
        end   

    end

end

However brace {} referencing doesn't work. I run this code

clear all
x = TimeStampValue(magic(3));
x{1:2}

and I get this error:

Error using TimeStampValue/subsref
Too many output arguments.
Error in main (line 3)
x{1:2} 

MException.last gives me this info:

identifier: 'MATLAB:maxlhs'
   message: 'Too many output arguments.'
     cause: {0x1 cell}
     stack: [1x1 struct]

which isn't helpful because the only thing in the exception stack is the file containing three lines of code that I ran above.

I placed a breakpoint on the first line of the switch statement in subsref but MATLAB never reaches it.

Whats the deal here? Both () and . referencing work as you would expect, so why doesn't {} referencing work?

4 Answers
Related