How to preallocate an array of class in MATLAB?

后端 未结 4 1904
时光取名叫无心
时光取名叫无心 2020-11-30 13:29

I have an array of objects in MATLAB and I\'ve called their constructors in a loop:

antsNumber  = 5;
for counter = 1: antsNumber
    ant(counter) = TAnt(sour         


        
4条回答
  •  日久生厌
    2020-11-30 14:20

    Not sure if I got your problem right, but if you want to initialize an array of your self-defined class "TAnt", here is how I would do it

    1. For TAnt's constructor method, put something like:

    function obj = TAnt(source, target)
             if nargin > 0
                  obj.mySource = source;
                  obj.myTarget = target;
             else
                  obj.mySource = defaultValue;
                  obj.myTarget = defaultValue;
             end
        end

    Then to initialize/pre allocate an array of default TAnt objects,

    ants(1,n) =  TAnt();  % n is the length of your ants array

提交回复
热议问题