MATLAB: Fast method to append or prepend rows of zeros

appendappend rowsMATLABprependprepend rows

Hi,
I have a 5001 by 762 matrix called posData. I would like to append and prepend, respectively, rows of zeros to posData. The number of rows appended and prepended to posData is given by a loop variable w, which ranges from 0 to 5001 in steps of 1.
For example, assuming that posData is a 5001 by 762 matrix, I have the following code:
tic
numColumns=size(posData,2);
for w=0:5001
firstM=[zeros(w,numColumns);posData];
secondM=[posData;zeros(w,numColumns)];
% perform operations on firstM and secondM
end
toc
Without doing any operations on the matrices firstM and secondM, the elapsed time on my computer is 713.175384 seconds. This seems like quite an expensive routine. Can you help me think if there is a faster way to do the above routine?
The other day, Walter pointed out to me that columns (and not rows) are contiguous in memory, so perhaps it would be faster to transpose my entire posData matrix and then prepend and append columns instead of rows. However, this will make the user input a bit more complicated. Is there any way to avoid transposing and yet still do the above routine more efficiently?
Thank you very much.
Andrew DeYoung
Carnegie Mellon University

Best Answer

Preallocate firstM & secondM outside of loop e.g.
firstM = zeros(10002,762);