How to preallocate an array of class in MATLAB?

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

    The warning it gives is superfluous, unless you are doing computational heavy stuff, I would ignore it.

    The reason why it's giving you the error, is because it has to find new space. Say, I give you a list of seven objects, and I tell you that you need to place them all in a row, I then go off, and give you a few more things you need to put somewhere. I then give you an eighth object and tell you to put it right after the seventh. Because you have stuff where the eighth object is, you either have to move it out of the way, or you have to move all seven objects. Matlab, is telling you it would be faster if you were to tell it beforehand that you want to put 5 things in there, rather than just giving it things one by one, having to look for a new spot each time. You can do that by adding this line to the top of your code:

    ant = [1:5];
    

    There are also other ways to do this too.

提交回复
热议问题