user2321808
user2321808

Reputation:

MATLAB: Not enough input arguments in constructor when creating object array

I have the following sample code.

classdef test < handle
  properties
    p1;
    p2;
    p3;
  end

  methods
    function obj=test(p1, p2, p3)
      obj.p1=p1;
      obj.p2=p2;
      if nargin<4
        obj.p3=0;
      else
        obj.p3=p3;
      end
    end
  end
end

Now if I do

m=test(1,1)

I get, as expected,

m = 

  test with properties:

    p1: 1
    p2: 1
    p3: 0

On the other hand, if I do

n=test.empty([0, 2, 2]);
n(1,1)=test(1,1);

I get

Error using test (line 10)
Not enough input arguments.

Same happens with n(1,1)=test(1,1,1).

I am really curious what is going wrong here. Obviously if I give more than 3 arguments, then I get Too many input arguments.

EDIT

I am using MATLAB R2013a.

Upvotes: 1

Views: 1154

Answers (1)

Trogdor
Trogdor

Reputation: 1346

Generally you can use the matlab debugging tools to solve this kind of problem. I copied your code and put a breakpoint in at line 10 to see what is happening.

In your case, the code as written is constructing the entire array of objects when you execute this line

n(1,1) = test(1,1);

That line changes the size of the array from 0 x 2 x 2 to 1 x 2 x 2, so it tries to instantiate all 4 objects and has no arguments with which to initialize the last three objects.

To resolve the error, I suggest creating a new method, I called it .initialize.

classdef test< handle
    properties
        p1;
        p2;
        p3;
    end

    methods
        function obj=test()
        end
        function initialize(obj,p1,p2,p3)
            obj.p1=p1;
            obj.p2=p2;
            if nargin<4
                obj.p3=0;
            else
                obj.p3=p3;
            end
        end
    end
end

Then you can create the array, instantiate the objects, and then initialize each object.

n = test.empty([0 2 2]);
n(1,1) = test;
n(1,1).initialize(1,1);

Upvotes: 0

Related Questions