Matlab too many input arguments Error?
I am having a problem with Matlab programming. Id like trying to call a method from a class and my class is very simple like this
classdef Addition
properties
a;
b;
end
methods
function obj = Addition(a, b)
obj.a = a;
obj.b = b;
end
function add(c, d)
fprintf(c + d);
end
end
end
I initialized a and tried to call the add function
a = Addition(1, 2) a.add(2,4)
However, Matlab gives me an error like:
Error while using add / add Too many input arguments.
Can someone please tell me why this strange thing happened?
source to share
Whenever you define a method in your class, you must always pass an instance obj
as an argument. See the documentation here .
When working with class instances in Matlab, the code
a.add(2,4)
equivalent to
add(a, 2, 4)
Since you (mistakenly) defined your instance method as function add(c, d)
, Matlab detects 3 parameters instead of 2.
Your method declaration should be function add(obj, c, d)
.
Read a little more about static and instance methods to decide if you need one or the other.
Since you are not using any property in your method / function add
, it seems that you need a static method instead of an instance method.
source to share
I get this error when I use an existing class to create another and forget to change the constructor function name to match the new class name. For example, in the code below I forget to change OldClass
to NewClass
in NewClass
methods()
then I get this error. The problem will be solved if I correct the name.
classdef NewClass
properties()
end
methods()
function obj = OldClass()
end
end
I get this error a lot, so I thought about sharing the possible cause of this error in case it helps anyone.
source to share