Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 936
Michael A Avatar asked Dec 31 '13 20:12

Michael A


1 Answers

When overloading the curly braces {} to return a different number of output arguments than usual, it is also necessary to overload numel to return the intended number (1, in this case). UPDATE: As of R2015b, the new function numArgumentsFromSubscript was created to be overloaded instead of numel. The issue remains the same, but this function should be overloaded instead of numel as I describe in the original answer below. See also the page "Modify nargout and nargin for Indexing Methods". Excerpt:

When a class overloads numArgumentsFromSubscript, MATLAB calls this method instead of numel to compute the number of arguments expected for subsref nargout and subsasgn nargin.

If classes do not overload numArgumentsFromSubscript, MATLAB calls numel to compute the values of nargout or nargin.

More explanation of the underlying issue (need to specify number of output arguments) follows.


Original answer (use numArgumentsFromSubscript instead of numel for R2015b+)

To handle the possibility of a comma separated list of output arguments when indexing with curly braces, MATLAB calls numel to determine the number of output arguments from the size of the input indexes (according to this MathWorks answer). If the number of output arguments in the definition of overloaded subsref is inconsistent with (i.e. less than) the number provided by numel, you get the "Too many output arguments" error. As stated by MathWorks:

Therefore, to allow curly brace indexing into your object while returning a number of arguments INCONSISTENT with the size of the input, you will need to overload the NUMEL function inside your class directory.

Since x{1:2} normally provides two outputs (X{1},X{2}), the definition function x = subsref(B, S) is incompatible for this input. The solution is to include in the class a simple numel method to overload the builtin function, as follows:

function n = numel(varargin)
    n = 1;
end

Now the {} indexing works as intended, mimicking ():

>> clear all % needed to reset the class definition
>> x = TimeStampValue(magic(3));
>> x(1:2)
ans = 
    7.355996e+05
     8     3
>> x{1:2}
ans = 
    7.355996e+05
     8     3

However, overloading curly braces in this manner is apparently a "specific type of code that we [MathWorks] did not expect customers to be writing". MathWorks recommends:

If you are designing your class to output only one argument, it is not recommended that you use curly brace indexing that requires you to overload NUMEL. Instead, it is recommended you use smooth brace () indexing.

UPDATE: Interestingly, the R2015b release notes state:

Before MATLAB release R2015b, MATLAB incorrectly computed the number of arguments expected for outputs from subsref and inputs to subsasgn for some indexing expressions that return or assign to a comma-separated list.

With release R2015b, MATLAB correctly computes the values of nargout and nargin according to the number of arguments required by the indexing expression.

So perhaps this is now fixed?


An alternative solution that comes to mind is to change function x = subsref(B, S) to function varargout = subsref(B, S) and adding varargout=cell(1,numel(B)); varargout{1} = x;. As Amro noted in comments, pre-allocating the cell is necessary to avoid an error about an unassigned argument.

like image 106
chappjc Avatar answered Sep 30 '22 20:09

chappjc