A quick way to find additional vectors in MATLAB

I have a matrix of strings of Nbinary vectors, i.e.

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;
             ....       ]

where I would like to find combinations of strings that when added together will get me exactly:

[1 1 1 1 1]

Thus, in the example above, the combinations that will work are 1/3, 1/4/5and 2/6.

The code for this now:

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

But, as you could imagine, this takes some time, especially because of this combnk.

What could be a useful algorithm / function that can help me speed this up?

+4
source share
1 answer
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

To display your matches in a nice, stylized way:

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

This will give:

Matches found for string: 7.

: [2 6].

: [1 4 5].

: [1 3].

, 2 milliseconds.

+1

Source: https://habr.com/ru/post/1690201/


All Articles