问题描述
假设M
是一个矩阵,其中每一行代表N
个对象池(例如
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
如何有效地找到数字B
之前数字A
的所有行?
How can I efficiently find all the rows in which a number A
comes before a number B
?
例如A=1
和B=2
;我想检索第一行和第二行(其中1
在2
之前)
e.g., A=1
and B=2
; I want to retrieve the first and the second rows (in which 1
comes before 2
)
推荐答案
去那里:
[iA jA] = find(M.'==A);
[iB jB] = find(M.'==B);
sol = find(iA<iB)
请注意,这样做的原因是,根据问题说明,可以保证每个数字在每一行中都出现一次.
Note that this works because, according to the problem specification, every number is guaranteed to appear once in each row.
要查找具有给定前缀的M
行(按注释中的要求):假设prefix
是具有所查找前缀的向量(例如,prefix = [1 2]
):
To find rows of M
with a given prefix (as requested in the comments): let prefix
be a vector with the sought prefix (for example, prefix = [1 2]
):
find(all(bsxfun(@eq, M(:,1:numel(prefix)).', prefix(:))))
这篇关于查找A> B的行的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!