MATLAB Answers

Pre-allocation Warnings, how can I stop this warning?

8 views (last 30 days)
Paulo Oliveira
Paulo Oliveira on 8 Feb 2019
Answered: vik on 8 Feb 2019
Hi, I have this code, and is getting warnings about pre-allocation to speed up in this variables:numdia,mediasDiarias, how can I pre-allocate this 2 variables, to stop the warning, this is driving my crazy, because I hate warnings, and I tried a lot to the warning disappear.
function [mediasDiarias,mesano,numdia]=perfilhorariosmensal(valores,ano,mes,hor)
mediasDiarias = [];
numdia = [];
mesano{1} = 'HORAS';
contMeses =2;
k=1;
while k<size(valores,1)
som = zeros(24,1);
cont = zeros(24,1);
if ~isnan(valores(k))
som(hor(k)+1) = valores(k);
cont(hor(k)+1) = 1;
end
k=k+1;
while ( ano(k) == ano(k-1) ) && ( mes(k) == mes(k-1) )
if ~isnan(valores(k))
som(hor(k)+1) = som(hor(k)+1) + valores(k);
cont(hor(k)+1) = cont(hor(k)+1) + 1;
end
k=k+1;
if k == size(valores,1)
break;
end
end
mesano{contMeses} = [n2s(mes(k-1),'%02d') '/' n2s(ano(k-1),'%04d')];
%mediasDiarias = [mediasDiarias som];%./cont];
mediasDiarias = [mediasDiarias som./cont];
numdia = [numdia (sum(cont)/24)];
contMeses=contMeses+1;
%pause
end
end

  0 Comments

Sign in to comment.

Accepted Answer

vik
vik on 8 Feb 2019
You just need to follow the warning and pre-allocate the memory and make some small changes to your code.
Instead of putting togehter arrays by using numdia = [numdia sum(cont)/24] which will change the numdia-array every iteration, always pre-allocate it first by assigning a zero-array which has the exact size your array should have at the end and use indexing then to assign values.
Basically you just need to know which size the array will have at the end of all your loops and assign it first.
numdia = zeros(1,size(valores,1)); % Pre-allocate memory by assigning a zero-array first
for k = 1:size(valores,1)
% ... more code here ...
numdia(k) = sum(cont)/24
end

  0 Comments

Sign in to comment.

More Answers (0)

Sign in to answer this question.


Translated by