根据第二个矩阵中的值过滤矩阵行 [英] Filter matrix rows depending on values in a second matrix
本文介绍了根据第二个矩阵中的值过滤矩阵行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出2x3矩阵x
和4x2矩阵y
,我想使用y
的每一行索引到x
.如果x
中的值不等于-1
,我想从y
中删除该行.这是一个可以满足我需求的示例,除了我想以一种快速,简单的方式来实现而没有循环.
Given a 2x3 matrix x
and a 4x2 matrix y
, I'd like to use each row of y
to index into x
. If the value in x
is not equal to -1
I'd like to remove that row from y
. Here's an example that does what I'd like, except I'd like to do it in a fast, simple way without a loop.
x = [1, 2, 3; -1, 2, -1];
y = [1, 1; 1, 3; 2, 1; 2, 3];
for i=size(y,1):-1:1
if x(y(i,1), y(i,2)) ~= -1
y(i,:) = [];
end
end
结果是:
y =
2 1
2 3
推荐答案
A raw approach to what sub2ind
follows (as used by this pretty nice-looking solution posted by Luis) inherently would be this -
y = y(x((y(:,2)-1)*size(x,1)+y(:,1))==-1,:)
基准化
基准代码
Benchmarking
Benchmarking Code
N = 5000;
num_runs = 10000;
x = round(rand(N,N).*2)-1;
y = zeros(N,2);
y(:,1) = randi(size(x,1),N,1);
y(:,2) = randi(size(x,2),N,1);
disp('----------------- With sub2ind ')
tic
for k = 1:num_runs
y1 = y(x(sub2ind(size(x), y(:,1), y(:,2)))==-1,:);
end
toc,clear y1
disp('----------- With raw version of sub2ind ')
tic
for k = 1:num_runs
y2 = y(x((y(:,2)-1)*size(x,1)+y(:,1))==-1,:);
end
toc
结果
----------------- With sub2ind
Elapsed time is 4.095730 seconds.
----------- With raw version of sub2ind
Elapsed time is 2.405532 seconds.
这篇关于根据第二个矩阵中的值过滤矩阵行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文