algorithm - 在 MATLAB 中快速查找互补向量的方法

标签 algorithm matlab combinations

我有一个由 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/31/4/52/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/

相关文章:

matlab - Octave生成组合子集

c# - 查找文本中完全匹配的所有关键字及其索引c#

java - 如何使用 matlabcontol.jar 从 java(适用于 android)运行 matlab 脚本

matlab - 从图像中裁剪椭圆

Matlab - 投票矩阵

python - 给定列表中项目的组合

c++ - 二元变量的排列及其值表

algorithm - 解码用过时语言压缩的文件

algorithm - 使用 Fisher-Yates shuffle 从链表中获取 k 个随机值

algorithm - 从加权图中选择边,使得每个顶点都是一条边的端点,并且边权重之和最小