2

我正在编写一段代码,它应该在 Nx3 矩阵E中找到包含 Mx3 矩阵值的行T,但它们的顺序不一定相同。我写了一些有效的东西,但我对这种风格不满意,并希望使用ismemberand find 对矩阵应用逻辑运算,而不是我正在使用的循环:

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

我的想法是对 and 的每一行进行排序ET因此它们的顺序相同,然后将每一行与循环进行比较。但是,我正在尝试学习以更 MATLAB 风格编写我的代码,并希望应用ismember并可能找到执行相同的操作。像这样的东西:

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);

还有更优雅的解决方案吗?

谢谢!

4

2 回答 2

3

You can use ismember with the 'rows' option:

ismember(sort(E, 2), sort(T, 2), 'rows')

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.

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')

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!).

Example

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');

The result is:

tf =          loc =
     1              1
     0              0
     0              0
     0              0
     1              2
于 2013-05-26T10:29:09.283 回答
1

你可以做你要求使用bsxfuneq功能:

Esorted = sort(E, 2);
Tsorted = sort(T, 2);

rowsEq = bsxfun(@eq, Esorted, permute(Tsorted, [3 2 1]));
rowsEqInd = sum(rowsEq, 2) == size(T, 2);
EEqInd = sum(rowsEqInd, 3) > 0;

无需在循环中对每一行进行排序 -E将为您执行此操作。是一个 3-D 数组,表示 的每一行中的元素与 的每一行的相等性;其中这个矩阵有一行 3 个s,和的行是相等的,所以我们总结并测试s 的个数是 3(或)。我们留下了一个数组,分别表示 T 的每一行的相等性,因此最终将这些结果结合起来给出您想要的结果。TsortrowsEqTE1ET1size(T, 2)sum

于 2013-05-26T10:10:41.830 回答