Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preallocate an array of class in MATLAB?

Tags:

oop

matlab

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(source, target);
end

MATLAB warns me to use preallocation to speed up the process. I do know the benefits of preallocation but I don't know how to do that for objects.

like image 465
Kamran Bigdely Avatar asked Mar 24 '10 18:03

Kamran Bigdely


People also ask

How do you pre allocate an array?

To pre-allocate an array (or matrix) of numbers, you can use the "zeros" function. To pre-allocate an array (or matrix) of strings, you can use the "cells" function. Here is an example of a script showing the speed difference. Make sure you "clear" the array variable if you try the code more than once.

How do you initialize an array in Matlab?

Array Creation To create an array with four elements in a single row, separate the elements with either a comma ( , ) or a space. This type of array is a row vector. To create a matrix that has multiple rows, separate the rows with semicolons.


2 Answers

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.

like image 137
gnovice Avatar answered Sep 22 '22 15:09

gnovice


The following link might be of help:

http://www.mathworks.com/help/techdoc/matlab_oop/brd4btr.html#brd4nrh
Web archive of dead link

New link:
http://de.mathworks.com/help/matlab/matlab_oop/creating-object-arrays.html

like image 41
Waleed Al-Balooshi Avatar answered Sep 26 '22 15:09

Waleed Al-Balooshi