查找矩阵中行的排列 [英] Find permutations of rows in matrix
问题描述
我正在编写一段代码,该代码应该在Nx3矩阵E
中查找包含Mx3矩阵T
的值的行,但是它们不一定是相同的顺序.我写了一些有效的东西,但是我对样式不满意,希望使用ismember
和find而不是我正在使用的循环在矩阵上进行逻辑运算:
I am writing a piece of code that is supposed to find the rows in Nx3 matrix E
that contains the values of Mx3 matrix T
, but they are not necessarily in the same order. I wrote something which is working, but I am not happy with the style and wish to apply logical operations on the matrices using ismember
and find, rather than the loop I am using:
E = [7 36 37; 9 1 5; 4 34 100; 4 12 33; 4 34 33];
T = [37 7 36; 4 34 33];
for i=1:size(T,1)
T(i,:) = sort(T(i,:));
end
for i=1:size(E,1)
E(i,:) = sort(E(i,:));
end
res = zeros(size(T,1),1);
for i=1:size(T,1)
a = ismember(E,t(i,:));
res(i,1) = find(sum(a,2)==3);
end
我的想法是对E
和T
的每一行进行排序,因此它们的顺序相同,然后将每个行与一个循环进行比较.但是,我试图学习以更MATLAB风格编写代码,并希望应用ismember
并可能会发现执行相同的操作.像这样:
My idea was to sort each row of E
and T
, so they will be in the same order and then compare each row with a loop. However, I am trying to learn to write my code in a more MATLAB-style and wish to apply ismember
and maybe find to do the same operation. Something like this:
a = sum(ismember(E,T(1,1))~=0,2);
b = sum(ismember(E,T(1,2))~=0,2);
c = sum(ismember(E,T(1,3))~=0,2);
r = find(a&b&c);
还有更优雅的解决方案吗?
Any more graceful solutions?
谢谢!
推荐答案
您可以使用这将产生一个逻辑(布尔)向量,该向量指示矩阵T
的哪些行(或其任何排列)出现在矩阵E
中.请注意,每一行都是独立排序的,以处理重新排序.
This produces a logical (boolean) vector that indicates which rows of matrix T
(or any of their permutations) appear in matrix E
. Note that each row is sorted independently to handle reordering.
如果需要T
行的索引,请同时使用ismember
的两个输出:
If you need the indices of the row of T
, use both outputs of ismember
:
[tf, loc] = ismember(sort(E, 2), sort(T, 2), 'rows')
注意:如果您的数据包含浮点数,则ismember
方法可能会失败,因此您需要设置比较公差.请参见此答案以获取更可靠的替代方法(并记住沿2 nd对输入矩阵进行排序首先是尺寸!).
Note: if your data contains floating-point numbers, the ismember
approach might fail, so you'll need to set a tolerance for comparison. See this answer for a more robust alternative approach (and remember to sort your input matrices along the 2nd dimension first!).
E = [7 36 37; 9 1 5; 4 34 100; 4 12 33; 4 34 33];
T = [37 7 36; 4 34 33];
[tf, loc] = ismember(sort(E, 2), sort(T, 2), 'rows');
结果是:
tf = loc =
1 1
0 0
0 0
0 0
1 2
这篇关于查找矩阵中行的排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!