[英]MATLAB Efficiently find the row that contains two of three elements in a large matrix
I have a large matrix, let's call it A, which has dimension Mx3, eg M=4000 rows x 3 columns. 我有一个大矩阵,我们称它为A,其尺寸为Mx3,例如M = 4000行×3列。 Each row in the matrix contains three numbers, eg.
矩阵中的每一行包含三个数字,例如。 [241 112 478].
[241 112 478]。 Out of these three numbers, we can construct three pairs, eg.
在这三个数字中,我们可以构造三对,例如。 [241 112], [112 478], [241 478].
[241 112],[112 478],[241 478]。 Of the other 3999 rows:
在其他3999行中:
Here's a function that accomplishes this, but is very slow - I'd like to know if there is a more efficient way. 这是一个实现这一目标的功能,但速度很慢 - 我想知道是否有更有效的方法。 Thanks in advance!
提前致谢!
M=size(A,1); % no elements
B=zeros(M,3);
for j=1:M
l=1;
k=1;
while l<4 % there cant be more than 3
if k~=j
s=sum(ismember(A(j,:),A(k,:)));
if s==2
B(j,l)=k;
l=l+1;
end
end
k=k+1;
end
For loops are not needed, just use ismember
the following way: 对于不需要的循环,只是用
ismember
方式如下:
row_id1=find(sum(ismember(M,[241 112]),2)>1);
row_id2=find(sum(ismember(M,[478 112]),2)>1);
row_id3=find(sum(ismember(M,[478 241]),2)>1);
each row_id
will give you the row index of the pair in that line regardless of the order at which it appears. 每个
row_id
将为您提供该行中该对的行索引,而不管它出现的顺序如何。
The only assumption made here is that one of the pair numbers you look for will not appear twice in a row, (ie [112 333 112]
). 这里唯一的假设是你寻找的一对数字不会连续出现两次(即
[112 333 112]
)。 If that assumption is wrong, this can be addressed using unique
. 如果这个假设是错误的,可以使用
unique
来解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.