consider preallocating for speed

15 views (last 30 days)
fatih goncagül
fatih goncagül on 22 Jun 2020
Commented: Voss on 3 Jul 2024
Hey there!!!!I am getting this preallocation warning.How can i fix this??Need your help!!
close all;
clear;
figure;
n=100000;
p=.301;
q=.15;
beta=10;
lambda=3;
timeofprobabilityestimation=60;
interval=.1;
for c=[400 500 600 700]
i=1;
pest=[];
totaltime=zeros(n,1);
for k=1:n
x=sum(rand(c,1)<p);
y=ceil(log(1-rand(x,1))/log(1-q));
totaltasks=sum(y);
t=sum(-1/lambda * log(rand(beta,totaltasks)));
totaltime(k)=sum(t);
end
for timeval=0:60*interval:60*100
pest(i)=mean(totaltime<timeval);%this is where i get warning
i=i+1;
end
timeval=0:interval:100;
plot(timeval,pest)
hold on;
end
legend('400', '500' ,'600', '700')
title('Total time vs probability')
xlabel('total time less than h')
ylabel('probability')
  2 Comments
Adam Danz
Adam Danz on 22 Jun 2020
If you share the complete warning message it may save us a lot of time looking for what may have triggered the warning.
fatih goncagül
fatih goncagül on 22 Jun 2020
Thanks for checking out Adam! This is the warning: The variable 'pest' appears to change size on every loop iteration (within a script). Consider preallocating for speed.Details

Sign in to comment.

Accepted Answer

Voss
Voss on 22 Jun 2020
This warning means that when you are calculating a vector or matrix element-by-element in a loop, MATLAB performs faster if the vector or matrix is initialized first, meaning that an amount of memory is allocated for the whole vector or matrix variable rather than memory for a single element having to be allocated each time the loop iterates. Obviously you can only preallocate if you know what size the vector or matrix will be before the loop starts, which luckily is the case in this case.
So when you initialize the variable pest, instead of setting it to be empty, you can set it to have 1001 elements (the number of iterations of the timeval loop). It doesn't matter what the value of pest is before the loop because each element will be overwritten by the loop, so it is customary to initialize with zeros:
% pest = []; % not preallocated
pest = zeros(1,100/interval+1); % preallocated to the correct size
  2 Comments
fatih goncagül
fatih goncagül on 22 Jun 2020
Edited: Voss on 3 Jul 2024
Thanks a lot @Voss.It's done.It was giving me headaches!!!1

Sign in to comment.

More Answers (0)

Categories

Find more on Performance and Memory in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!