Fast method to append or prepend rows of zeros

5 views (last 30 days)
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
  1 Comment
bym
bym on 22 May 2011
you realize the first time through the loop you are appending & prepending with an empty matrix...

Sign in to comment.

Accepted Answer

bym
bym on 22 May 2011
Preallocate firstM & secondM outside of loop e.g.
firstM = zeros(10002,762);

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!