MATLAB: Efficiently Deleting Matrix Columns/Rows

manipulationMATLABmatrixmatrix manipulationmexperformance

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 thread 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!

Best Answer

The above code still works fine for me in R2015a Win32. Maybe you might change the mwSize to size_t, but unless the dimension is really large I don't see how this could make a difference. E.g. on my machine:
>> format debug
>> M = reshape(1:24,4,6)
M =
Structure address = 8a4fa88
m = 4
n = 6
pr = 33126c60
pi = 0
1 5 9 13 17 21
2 6 10 14 18 22
3 7 11 15 19 23
4 8 12 16 20 24
>> M_copy = M
M_copy =
Structure address = 8a4fd60
m = 4
n = 6
pr = 33126c60
pi = 0
1 5 9 13 17 21
2 6 10 14 18 22
3 7 11 15 19 23
4 8 12 16 20 24
>> deletelastcolumn(M)
>> M
M =
Structure address = 8a4fa88
m = 4
n = 5
pr = 33126c60
pi = 0
1 5 9 13 17
2 6 10 14 18
3 7 11 15 19
4 8 12 16 20
>> deletelastcolumn(M)
>> M
M =
Structure address = 8a4fa88
m = 4
n = 4
pr = 33126c60
pi = 0
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
>> M_copy
M_copy =
Structure address = 8a4fd60
m = 4
n = 6
pr = 33126c60
pi = 0
1 5 9 13 17 21
2 6 10 14 18 22
3 7 11 15 19 23
4 8 12 16 20 24
So things still seem to be working OK. There are no hacks in this simple code ... just an in-place dimension change. The data pointer stays the same throughout as expected. And the in-place dimension change on M does not affect the dimension of the shared data copy M_copy which has the same data pointer. Again, all is as expected. So I don't see why it would not work on any MATLAB version. What exactly are you seeing?