Using MatLab class methods without arguments



This site utilizes Google Analytics, Google AdSense, as well as participates in affiliate partnerships with various companies including Amazon. Please view the privacy policy for more details.

Sometimes in MatLab you’ll have a class, and you want to have a function or method in that class that modifies an instance variable in some way. But if you code your class like this:

Code:

1
2
3
4
5
6
7
8
9
10
	classdef my_class
	  properties
	    my_variable = 2;
	  end
	  methods
	    function doubleMyVariable()
	      my_class.my_variable = my_class.my_variable * 2;
	    end
	  end
	end

And you try to use that function once you made an object from your class:

Code:

1
2
	my_object = my_class;
	my_object.doubleMyVariable()

You’ll end up with a very annoying error like this:

Code:

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

WTF?!?!? There’s no arguements! Well, that’s because MatLab secretly passes the object itself as an arguement. So there’s always at least one arguement, even if you don’t specify it. To fix this, change your class definition to this:

Code:

1
2
3
4
5
6
7
8
9
10
	classdef my_class
	  properties
	    my_variable = 2;
	  end
	  methods
	    function doubleMyVariable(my_class)
	      my_class.my_variable = my_class.my_variable * 2;
	    end
	  end
	end

And your code should work. Couldn’t find this anywhere on the internet, so if you’re having this trouble, I hope this helps!

Until next time

Joe

2 comments for Using MatLab class methods without arguments

  • Reply to This Thread

  • Reply to This Thread

Leave a Reply

Note that comments won't appear until approved.