Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing rows and columns from MATLAB matrix quickly

Tags:

matlab

Is there a fast way to remove rows and columns from a large matrix in MATLAB?

I have a very large (square) distance matrix, that I want to remove a number of rows/columns from.

Naively:

s = 12000;
D = rand(s);
cols = sort(randsample(s,2))
rows = sort(randsample(s,2)) 

A = D;
tic
A(rows,:) = [];
A(:,cols) = [];
toc
% Elapsed time is 54.982124 seconds.

This is terribly slow though. Oddly, this is the fastest solution suggested at the bottom here.

An improvement can be made by preallocating the array and using boolean indices

A = zeros(size(D) - [numel(rows) numel(cols)]);
r = true(size(D,1),1);
c = true(size(D,2),1);
r(rows) = false;
c(cols) = false;

tic
A = D(r,c);
toc
% Elapsed time is 20.083072 seconds.

Is there still a faster way to do this?

like image 596
noio Avatar asked Nov 12 '10 10:11

noio


People also ask

How do you clear a matrix in Matlab?

Open Excel and make sure cell A1 is selected in the worksheet. Delete the matrix A using the MLDeleteMatrix function. Enter this text in the cell and press Enter. The MLDeleteMatrix function deletes the matrix from the MATLAB Workspace.

How do I extract the number of rows in Matlab?

Direct link to this comment If for example your matrix is A, you can use : size(A,1) for number of rows. size(A,2) for number of columns. Also there are some other ways like : length ( A(:,1) ) for number of rows.

How do you separate a row from a matrix in Matlab?

Direct link to this answer For Splitting a matrix in a loop You can use the colon operator. M(3:4, :) % 3rd and 4th row of M and all columns. If you want to split any number of columns in multiple matrices of two colums, You can use a for loop to do so.


1 Answers

It seems like a memory bottleneck. On my feeble laptop, breaking D up and applying these operators to each part was much faster (using s=12,000 crashed my computer). Here I break it into two pieces, but you can probably find a more optimal partition.

s = 8000;
D = rand(s);

D1 = D(1:s/2,:);
D2 = D((s/2 + 1):end,:);

cols = sort(randsample(s,2));
rows = sort(randsample(s,2));

A1 = D1;
A2 = D2;

tic
A1(rows(rows <= s/2),:) = [];
A2(rows(rows > s/2) - s/2,:) = [];
A1(:,cols) = [];
A2(:,cols) = [];
toc

A = D;
tic
A(rows,:) = [];
A(:,cols) = [];
toc

Elapsed time is 2.317080 seconds.
Elapsed time is 140.771632 seconds.
like image 110
MarkV Avatar answered Oct 23 '22 19:10

MarkV