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

后端 未结 4 1887
别跟我提以往
别跟我提以往 2021-02-09 14:09

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

4条回答
  •  清酒与你
    2021-02-09 14:42

    I just ran into the same problem. What's even worse, is that the number of output arguments is enforced to be equal to what numel() returns not only for the curly braces {}, but also for the dot . operation.

    This means that if numel() is overridden to return the usual prod(size(obj)), it becomes impossible to access any properties of the underlying object (such as x.time in the above example), as subsref() is then expected to return multiple outputs.

    But if numel() just returns 1 instead, it does not match prod(size(obj)), which is what most code working with numeric values or based on reshape() expects. In fact, the MATLAB editor's balloon help immediately suggests that 'NUMEL(x) is usually faster than PROD(SIZE(x))', which suggest that they are equivalent, but apparently are not.

    A possible solution would be to make numel() return prod(size(obj)) and write explicit getter/setter functions for all these properties, e.g.,

    x.get_time()
    

    in the example above. This seems to work, because method calls apparently get resolved before subsref() gets called. But then if one of the properties is a matrix it cannot be directly indexed any more because Matlab doesn't understand chained indexing, i.e., instead of writing

    x.matrix(1,:)
    

    one would have to write

    m = x.get_matrix();
    m(1,:)
    

    which is ugly to say the least.

    This is starting to get a bit frustrating. I still hope I've just overlooked something obvious, I can't believe that this is how it's supposed to work.

提交回复
热议问题