Fast way to delete the last n rows of a matrix

조회 수: 38 (최근 30일)
Andrew
Andrew 2011년 5월 20일
댓글: Walter Roberson 2020년 3월 7일
Hi,
I would like to be able to delete the last n rows of a matrix. I have found that this can be done in the following way. For example, suppose I want to delete the last two rows of a matrix:
tst=[1 1 1; 2 2 2; 3 3 3];
lastn=2;
tic
tst((end-(lastn-1)):end,:)=[];
toc
This works, but it seems quite expensive: "Elapsed time is 0.001152 seconds." In my code, I will be deleting rows many hundreds of thousands of times. Do you know if there is a faster way to delete the last n rows of a matrix?
Thank you.
Andrew DeYoung
Carnegie Mellon University

채택된 답변

Sean de Wolski
Sean de Wolski 2011년 5월 20일
tst = tst(1:end-lastn,:); %glass half full
No guarantees it'll be faster. The typical goal here is just minimize the number of matrix resizing operations you have to do.
  댓글 수: 3
Hafsa Arif
Hafsa Arif 2020년 3월 7일
is this making a new one? informmation will be lost or get arranged in the matrix?
Walter Roberson
Walter Roberson 2020년 3월 7일
Newtst = tst(1:end-lastn,:); %glass half full
If you want to keep the old matrix. With Sean's version to write to tst then the last rows would be thrown away.

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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2011년 5월 20일
Andrew, could you transpose so that you are deleting columns instead of rows? If you do that then the portion that is left behind is contiguous in memory, and it should be faster to work with that than to have to copy over each partial column as you delete rows.
  댓글 수: 3
Walter Roberson
Walter Roberson 2011년 5월 20일
Correct. MATLAB arranges memory in columns and the first entry for the next column is stored in memory directly after the last entry for this column. Therefor if you are keeping entire columns then the block of memory that needs to be copied to the new array is arranged sequentially in memory and can just be described as "starting address" and "number of items to copy". Especially for larger blocks, there are often ways to optimize that at the machine level, such as by copying full system "pages" of memory using DMA.
Andrew
Andrew 2011년 5월 20일
Thank you so much. I really appreciate your taking the time to explain this to me. I will be able to use in the future what you have taught me.

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

카테고리

Help CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by