How to pre-allocate an empty matrix ?
Show older comments
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 ?
2 Comments
Greg
on 10 Apr 2017
Regardless of pre-allocation,
appnd_data = [appnd_data;e.(s.labs{m})(:,l)];
Makes "appnd_data" larger every time it is called. It is more efficient to use indexing on the left side of the statement to fill in the appropriate portion of the pre-allocated matrix.
Run the "whos" command after line 2 and at the very end. You'll see the size in bytes of "appnd_data" grows.
Stephen23
on 10 Apr 2017
"Does line 2 not pre-allocate it ?" No, it does not. Read the MATLAB documentation to know more:
Accepted Answer
More Answers (1)
Roger Stafford
on 10 Apr 2017
Edited: Roger Stafford
on 10 Apr 2017
Rather than stacking your ‘appnd_data’ successively by:
for m = 1:length(s.labs)
appnd_data = [appnd_data;e.(s.labs{m})(:,l)];
end
OVR_MEAN(:,l) = mean(appnd_data);
it should instead be done this way:
ix = 0;
for m = 1:length(s.labs)
t = e.(s.labs{m})(:,l);
append_data(ix+1:ix+size(t,1)) = t;
ix = ix+size(t,1);
end
OVR_MEAN(:,l) = mean(appnd_data(1:ix));
Before doing this you should allocate enough memory for ‘append_data’ for the longest of these final ix values using the ‘zeros’ function.
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!