General Threshhold/rule of thumb for preallocation?
7 views (last 30 days)
I've been going over my code slowly dealing with all problems found by the code analyzer. I've now looked into preallocation, as there are several matrices that grow inside for or while loops. I understand why you should preallocate the space if you know that said matrix will become bigger.
Out of these growing matrices, there is only really one that will really grow big.
LPcolors=zeros([5000 3]); %% this line is a bit earlier, but the code in-between is irrelevant here.
LPcolors=[1 0 0; % redold %% % It could be smaller I suppose, this is already way over what I'd argue to be sensible.
0 0 1; % blueo %% Also, 5000 is a rather arbitrary number and just a wild guess. As far as I can see,
0 1 0; % greeno %% it doesn't negatively influence performance if it is too big. Correct me if I am wrong.
0 1 1; % cyano
1 0 1; % magentao
0 0 0; % blacko
1 1 0; % yellowo
0, 0.4470, 0.7410 % bluenew
0.8500, 0.3250, 0.0980 % orangenew
0.9290, 0.6940, 0.1250 % yellownew
0.4940, 0.1840, 0.5560 % purplenew
0.4660, 0.6740, 0.1880 % greennew
0.3010, 0.7450, 0.9330 % lightbluenew
0.6350, 0.0780, 0.1840]; % brownnew
while LPNumColorRows<LPNumRows %% LPNumRows gives the number of plotted graphs/data sets that need to
LPcolors=[LPcolors;LPcolors]; %% have different colors. It is determined at the beginning as the size of a certain matrix that has to be provided by the user.
[LPNumColorRows,~]=size(LPcolors); %% I know this matrix LPcolors will outgrow the actually necessary number of rows quickly, but that is kinda the point.
In this case, I understand why preallocation makes sense.
However, I have some smaller matrices and 2 cell arrays that grow pretty slowly, and will usually not grow above 15x1.
At which point/size does it make sense to preallocate for a matrix etc? Is there a general rule-of-thumb or something?
I looked at the documentation on preallocation, and couldn't find an answer.
On an somewhat unrelated note, you guys have been incredible helpful in the creation of this thing. 70% of what I used was unknown to me, 20% I was rather bad at and 10% I could do before. And although the matlab documentation is rather good, without having the knowledge of where to look and what to look for, it is still rather hard to use.
So thank you for pointing me ways and explaining some stuff to some dude with too much free time, nothing to do and no real experience
in coding whatsoever. My code might still be crappy in some ways that I cannot see probably, but at least it's a lot better than before.
Thank you & stay healthy.