快速从MATLAB矩阵中删除行和列 [英] Removing rows and columns from MATLAB matrix quickly

查看:93
本文介绍了快速从MATLAB矩阵中删除行和列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种快速的方法可以从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.

天真:

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.

还有更快的方法吗?

推荐答案

这似乎是内存瓶颈.在我笨拙的笔记本电脑上,分解D并将这些运算符应用到每个零件上要快得多(使用s = 12,000使我的计算机崩溃).在这里,我将其分为两部分,但是您可能可以找到一个更好的分区.

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.

这篇关于快速从MATLAB矩阵中删除行和列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆