MATLAB: Fast way to delete the last n rows of a matrix

deletedeletingMATLABrows

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

Best Answer

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.