Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
869 views
in Technique[技术] by (71.8m points)

oop - How to preallocate an array of class in 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...