我有一个由 N
行二进制向量组成的矩阵,即
mymatrix = [ 1 0 0 1 0;
1 1 0 0 1;
0 1 1 0 1;
0 1 0 0 1;
0 0 1 0 0;
0 0 1 1 0;
.... ]
我想在哪里找到行的组合,当它们加在一起时,我会得到准确的信息:
[1 1 1 1 1]
所以在上面的示例中,可行的组合是 1/3
、1/4/5
和 2/6
.
我现在拥有的代码是:
i = 1;
for j = 1:5
C = combnk([1:N],j); % Get every possible combination of rows
for c = 1:size(C,1)
if isequal(ones(1,5),sum(mymatrix(C(c,:),:)))
combis{i} = C(c,:);
i = i+1;
end
end
end
但是正如您想象的那样,这需要一段时间,特别是因为那里的 combnk
。
有什么有用的算法/函数可以帮助我加快速度?
最佳答案
M = [
1 0 0 1 0;
1 1 0 0 1;
0 1 1 0 1;
0 1 0 0 1;
0 0 1 0 0;
0 0 1 1 0;
1 1 1 1 1
];
% Find all the unique combinations of rows...
S = (dec2bin(1:2^size(M,1)-1) == '1');
% Find the matching combinations...
matches = cell(0,1);
for i = 1:size(S,1)
S_curr = S(i,:);
rows = M(S_curr,:);
rows_sum = sum(rows,1);
if (all(rows_sum == 1))
matches = [matches; {find(S_curr)}];
end
end
以良好的程式化方式显示您的比赛:
for i = 1:numel(matches)
match = matches{i};
if (numel(match) == 1)
disp(['Match found for row: ' mat2str(match) '.']);
else
disp(['Match found for rows: ' mat2str(match) '.']);
end
end
这将产生:
Match found for row: 7.
Match found for rows: [2 6].
Match found for rows: [1 4 5].
Match found for rows: [1 3].
就效率而言,在我的机器中,该算法在大约 2 毫秒
内完成匹配检测。
关于algorithm - 在 MATLAB 中快速查找互补向量的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47620451/