I just got a problem with matlab programming. I’d like to try 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 initialised a and try to call the add function by
a = Addition(1, 2)
a.add(2,4)
However, matlab gives me the error as:
Error using Addition/add
Too many input arguments.
Could somebody please tell me why this strange thing happened?
Whenever you are defining a method in your class, you must always pass the instance obj
as argument. See the documentation here.
When working with instances of classes in Matlab, the code
a.add(2,4)
is equivalent to
add(a, 2, 4)
Since you (wrongly) defined your instance method as function add(c, d)
Matlab is detecting 3 parameters instead of 2.
Your method declaration must be function add(obj, c, d)
.
Read a bit more about static methods and instance methods to decide whether you need one or the other.
Since you are not using any property in your method/function add
, it seems that you want a static method instead of an instance method.
I get this error when I use an existing class for creating another and forget to change the constructor function name as per new class name. For example in the code below, if I forget to change OldClass
to NewClass
under methods()
then I get this error. Issue resolves if I correct the name.
classdef NewClass
properties()
end
methods()
function obj = OldClass()
end
end
end
I end up getting this error often, so thought of sharing a possible cause of this error if it helps someone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With