Search code examples
functionoopmatlabmatlab-deployment

Matlab: Instantiate the handle class inside a function within another class


Let's say, for instance, I have two classes: A & B. I have set B as the handle class and would like a property from A to instantiate this class (i.e. B).

Therefore, I have done something like this in class A:

% Constructor
function a = A()
   a.objB = B(); % This works fine

   ...

   for i = 1:10
      a.var(i) = B(); % This causes an error to occur
   end
end

The error is listed below:

"Error using double Conversion to double from B is not possible.

The code snippet inside the for loop seems to work if I change a.var(i) = B(); to var(i) = B();.

Do you have any idea why this is?


Solution

  • Your .var field is probably initialized to a double when you make the assignment (maybe to []). Using a.var(i) = xxx cannot change the type of a.var.

    Try resetting the value the first time it is used. EG

    for i = 1:10
        if i == 1
            a.var = B(); % Overwrite the existing value
        else
            a.var(i) = B(); % Now append to that value
        end
    end
    

    This will cause your a.var field to be reallocated every loop. Pre-allocated your array will make everything go much faster. The easiest way to pre-allocate is actually to just loop backwards, like this:

    for i = 10:-1:1
        if i == 10
            a.var = B(); % Overwrite the existing value, allocated room for 10 elements
        else
            a.var(i) = B(); % Assign each element in turn, 9 through 1
        end
    end