mHelpMe
mHelpMe

Reputation: 6668

calling a class method - too many input arguments

I have a created a simple class to try and learn more about classes in MATLAB

Below is my class.

classdef ClassTest < handle

methods             
   function t1 = testone(numOne, numTwo)
      t1 = t2(numOne, numTwo); 
   end

   function t2 = testtwo(numOne, numTwo)
       t2 = numOne / numTwo;
   end
end

end

So I create an instance of my class using the line of code below.

myClass = ClassTest;

I then call the function testone with the line below.

v = myClass.testone(20,5);

But get the error message "Error using ClassTest/testone Too many input arguments." I don't understand this?

I tried leaving the 5 out and it actually got to the line t1 = t2(numOne, numTwo) but then didn't recognize the function t2 which I find surprising? Not following what is going on here?

Update

If I make the methods static I no longer get the error message about there being to many input arguments however it does not recognise the testtwo function when called from the function testone unless I put ClassTest.testtwo. Still seems strange to me

Solution

So bit of playing around I now have the code working however not sure I fully understand what is happening.

The two functions should look like below,

   function t1 = testone(obj, numOne, numTwo)
      t1 = obj.testtwo(numOne, numTwo);           
   end

   function t2 = testtwo(obj, numOne, numTwo)
       t2 = numOne / numTwo;
   end

Upvotes: 0

Views: 546

Answers (2)

Sam Roberts
Sam Roberts

Reputation: 24147

If you want the methods to be static methods of the class, then define them within a methods block as follows:

methods (Static)

You will then need to call them with the class name as t1 = ClassTest.testone(20,5) and t2 = ClassTest.testtwo(20,5).

If instead you want them to be methods of the class, then you would typically define them with the following signature:

function t1 = testone(obj, numOne, numTwo)

You can then create an instance of the class with myClass = ClassTest and call t1 = myClass.testone(20,5).

The object myClass is passed into the method as its first argument (I always use the name obj as a first argument, but others use things such as this, by analogy with Java conventions), and is then available throughout the method code.

Upvotes: 1

klurie
klurie

Reputation: 1060

This may have to do with how matlab loads classes. If you already have myClass in memory and then you create/modify the function definitions, you will likely get an error.

here is more details on how matlab deals with updating classes: http://www.mathworks.com/help/matlab/matlab_oop/modifying-and-reloading-classes.html

Try clearing all your variables from memory (and as a last resort restarting matlab), and try again.

Upvotes: 0

Related Questions