Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab, Too many input arguments Error?

Tags:

matlab

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?

like image 641
user3535716 Avatar asked Jan 10 '23 00:01

user3535716


2 Answers

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.

like image 168
gire Avatar answered Jan 19 '23 22:01

gire


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.

like image 29
Nafeez Quraishi Avatar answered Jan 19 '23 22:01

Nafeez Quraishi