MATLAB: How to pre-allocate an empty matrix

pre-allocate

here is part of my code…
...
for l = 1:length(WtLabDt)
appnd_data = [];
for m = 1:length(s.labs)
appnd_data = [appnd_data;e.(s.labs{m})(:,l)];
end
OVR_MEAN(:,l) = mean(appnd_data);
end
Matlab is showing light red lines under 'appnd_data' (in line 4 on lhs) asking me to pre-alloacte it for speed. Does line 2 not pre-allocate it ?

Best Answer

A pre-allocation would be:
size1 = cellfun('size', s.labs, 1);
appnd_data = zeros(sum(size1), 1);
iPos = 1;
for m = 1:length(s.labs)
fPos = iPos + size1(m);
appnd_data(iPos:fPos-1) = e.(s.labs{m})(:,l);
iPos = fPos;
end
But is there any reason to create this large vector, when all you want is to get its mean?
allSize1 = sum(cellfun('size', s.labs, 1));
S = 0;
for m = 1:length(s.labs)
S = S + sum(e.(s.labs{m})(:,l));
end
OVR_MEAN(:, l) = S / allSize1;
Perhaps I did not understand, why the vector OVR_MEAN(:, l) is assigned, although the result is a scalar. But the ideas should got clear now:
  1. Pre-allocation means reserving memory for the final array at once instead of letting the array grow iteratively
  2. If you can avoid to create large temporary arrays, do this.