views:

3365

answers:

2

I am working on some simple object-oriented code in MATLAB. I am trying to call one of my class methods with no input or output arguments in its definition.

Function definition:

function roll_dice

Function call:

obj.roll_dice;

When this is executed, MATLAB says:

??? Error using ==> roll_dice
Too many input arguments.

Error in ==> DiceSet>Diceset.Diceset at 11
obj.roll_dice;
(etc...)

Anyone have any ideas what could be causing it? Are there secret automatic arguments I'm unaware that I'm passing?

+7  A: 

When you make the call:

obj.roll_dice;

It is actually equivalent to:

roll_dice(obj);

So obj is the "secret" automatic argument being passed to roll_dice. If you rewrite the method roll_dice to accept a single input argument (even if you don't use it), things should work correctly.

Alternatively, if you know for sure that your method roll_dice is not going to perform any operations on the class object, you can declare it to be a static method as Dan suggests.

For more information on object-oriented programming in MATLAB, here's a link to the online documentation.

gnovice
Ie, roll_dict is being called as a method on an object when it shouldn't be. Try roll_dice() instead of obj.roll_dice().
Nikhil Chelliah
That might work, but he did say roll_dice is a class method, so I'm guessing it's intended to operate on a given object.
gnovice
You were right, but now I have a different problem. I'm coming from languages like Java and PHP where it is fairly straightforward to use classes. What is the equivalent of self.roll_dice or this.roll_dice?
farr
Most class methods I've seen are written to accept the object being operated on as the first argument. This first argument can be thought of as a "self" reference. I suggest this MATLAB documentation link for help: http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_oop/ug_intropage.html
gnovice
+1  A: 

I believe you can also get around this by declaring roll_dice to be a static method.

Dan
+1: Yes, if roll_dice is a static method then obj.roll_dice should work without needing to add any input arguments to the function definition.
gnovice