How to preallocate an array of class in MATLAB?

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.

Leave a Comment