Why do I get a "Too many output arguments" error when using a subclass of containers.Map?

3 views (last 30 days)
I made my own class which is a subclass of containers.Map. When I try to use a method I wrote for this class, I keep getting errors saying:
>> foo = myClass();
>> foo.myMethod();
Error using myClass/myMethod
Too many output arguments.
The definition of this method doesn't have any output arguments and I am not assigning the result of the method call to anything. Why am I getting an error about too many output arguments?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 10 Aug 2018
This error has to do with the "subsref" function in MATLAB. Whenever, we run some MATLAB code that uses . or ( ) or { } on an object, like so:
>> foo.x
>> foo(x)
>> foo{x}
MATLAB uses the "subsref" function to determine how many outputs to expect from the expression. Say we want our class to behave differently than this default behavior, we can define your own "subsref" method for your class. This is exactly what containers.Map does. It has its own version of "subsref" which allows us to index our map using ( ) in a different way compared to other MATLAB classes. You will also notice that using . or { } on a map acts differently than with other classes. If we create a subclass of containers.Map, this class will inherit this behavior which is where this error comes from.
There are two ways to resolve this error,
1) Make it so that every method defined in your class has at least one output argument. The "subsref" method for containers.Map assumes there will always be at least output argument for any method.
2) You can define your own "subsref" method in your class. This process is much more involved than the first workaround. These documentation pages give more details about "subsref" and how to define your own:

More Answers (0)

Categories

Find more on Graphics Object Programming in Help Center and File Exchange

Products


Release

R2014b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!