简体   繁体   中英

Efficiently Deleting Matrix Rows/Columns in MATLAB

Any tips on efficiently and quickly deleting a given row/column from a Matrix?

I had initially believed that deleting the last column of a given matrix would be more efficient than the first column, and all column operations would be more efficient than row operations (given MATLAB's column based memory), which I was able to confirm through testing. However, the performance I did get was rather unfortunate.

someB = rand(4,50000);
someC = someB.';

tic
while size(someB,2) > 2
   someB(:,size(someB,2)) = [];
end
toc

tic
while size(someC,1) > 2
   someC(size(someC,1),:) = [];
end
toc

%Elapsed time is 13.869280 seconds.
%Elapsed time is 10.198270 seconds.

I did a quick search and in this MATLAB newsgroup discussion I found hope that through external C MEX functions there may indeed be a way to efficiently delete the last column of a matrix quickly. The code is attached below.

#include "mex.h"

// You may need to uncomment the next line
//#define mwSize int

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{ 
  mwSize n;
  if( n = mxGetN(prhs[0]) )
      mxSetN(prhs[0], n - 1);
} 

However, I was not able to get said code running myself. If you take a quick look at the results that the author was finding, you'll find rather remarkable performance. I'm not that good at MEX myself; would anyone know how to fix above code so that it runs, or alternatively, have an equally/near equally good MEX code/MATLAB code performance-wise?

Thanks!

Well, for one, the MEX solution you posted isn't actually deleting the column, so it's not really a fair comparison. The solution of using "mxSetN" just sets the internal header for the mxArray to think that it has N columns. From the documentation:

You typically use mxSetN to change the shape of an existing mxArray. The mxSetN function does not allocate or deallocate any space for the pr, pi, ir, or jc arrays.

Regarding the timing results you're seeing, what happens if you run this multiple times? The first time I ran this I had similar results to yours, but on the second run the timings were similar for both methods.

Keep in mind that in either case, you have to reallocate a large amount of memory because you're only deleting 4 elements at a time. This means the earlier loop iterations will cost you more than the later iterations.

The big question here is what you're ultimately trying to do. Maybe you can avoid the deletion and just use the portion of the matrix you need, or maybe there's some way to avoid having to delete a single column on each iteration (and instead do multiple columns).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM