Fast method to append or prepend rows of zeros

조회 수: 4 (최근 30일)
Andrew
Andrew 2011년 5월 22일
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
bym
bym 2011년 5월 22일
you realize the first time through the loop you are appending & prepending with an empty matrix...

댓글을 달려면 로그인하십시오.

채택된 답변

bym
bym 2011년 5월 22일
Preallocate firstM & secondM outside of loop e.g.
firstM = zeros(10002,762);

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by