How to preallocate an array of class in MATLAB?

后端 未结 4 1896
时光取名叫无心
时光取名叫无心 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:13

    Here are a few options, which require that you design the class constructor for TAnt so that it is able to handle a no input argument case:

    • You can create a default TAnt object (by calling the constructor with no input arguments) and replicate it with REPMAT to initialize your array before entering your for loop:

      ant = repmat(TAnt(),1,5);  %# Replicate the default object
      

      Then, you can loop over the array, overwriting each default object with a new one.

    • If your TAnt objects are all being initialized with the same data, and they are not derived from the handle class, you can create 1 object and use REPMAT to copy it:

      ant = repmat(TAnt(source,target),1,5);  %# Replicate the object
      

      This will allow you to avoid looping altogether.

    • If TAnt is derived from the handle class, the first option above should work fine but the second option wouldn't because it would give you 5 copies of the handle for the same object as opposed to 5 handles for distinct objects.

提交回复
热议问题