1

Suppose M is a matrix where each row represents a randomized sequence of a pool of N objects, e.g.,

1 2 3 4
3 4 1 2
2 1 3 4

How can I efficiently find all the rows in which a number A comes before a number B?

e.g., A=1 and B=2; I want to retrieve the first and the second rows (in which 1 comes before 2)

4

2 回答 2

5

你去:

[iA jA] = find(M.'==A);
[iB jB] = find(M.'==B);
sol = find(iA<iB)

请注意,这是有效的,因为根据问题规范,每个数字都保证在每一行中出现一次。


要查找M具有给定前缀的行(如评论中所要求的):让prefix成为具有所寻求前缀的向量(例如,prefix = [1 2]):

find(all(bsxfun(@eq, M(:,1:numel(prefix)).', prefix(:))))
于 2013-10-09T16:14:11.897 回答
1

类似下面的代码应该可以工作。它将查看是否AB每一行中出现。

temp = [1 2 3 4;
        3 4 1 2;
        2 1 3 4];
A = 1;
B = 2;
orderMatch = zeros(1,size(temp,1));
for i = 1:size(temp,1)
    match1= temp(i,:) == A;
    match2= temp(i,:) == B;
    aIndex = find(match1,1);
    bIndex = find(match2,1);
    if aIndex < bIndex
        orderMatch(i) = 1;
    end
end
solution = find(orderMatch);

这将导致[1,1,0]因为前两行有 1 在 2 之前,但第三行没有。

更新

按照 Luis 的建议,在 ordermatch 上添加了find函数以提供行索引

于 2013-10-09T16:19:00.933 回答