Matlab: find row indexes with common elements

I have a matrix:

1 2 3 4 5 6 7 8 1 

How can I use matlab to find this:

for the first row: row3
for the 2nd row: ---
for the third row: row1

I want row indexes for each row to have common elements.

+4
source share
3 answers

Consider this

 A = [1 2 3; %Matrix A is a bit different from yours for testing 4 5 6; 7 8 1; 1 2 7; 4 5 6]; [row col] =size(A) answers = zeros(row,row); %matrix of answers,... %(i,j) = 1 if row_i and row_j have an equal element for i = 1:row for j = i+1:row %analysis is performed accounting for % symmetry constraint C = bsxfun(@eq,A(i,:),A(j,:)'); %Tensor comparison if( any(C(:)) ) %If some entry is non-zero you have equal elements answers(i,j) = 1; %output end end end answers = answers + answers'; %symmetric 

Result here

 answers = 0 0 1 1 0 0 0 0 0 1 1 0 0 1 0 1 0 1 0 0 0 1 0 0 0 

of course the answers matrix answers symmetric because your attitude there is.

+4
source

The solution offered by Acorbe can be quite slow if you have many lines and / or long lines. I checked that in most cases the two solutions that I cited below should be significantly faster. If your matrix contains only a few different values ​​(relative to the size of the matrix), then this should work pretty quickly:

 function rowMatches = find_row_matches(A) % Returns a cell array with row matches for each row c = unique(A); matches = false(size(A,1), numel(c)); for i = 1:numel(c) matches(:, i) = any(A == c(i), 2); end rowMatches = arrayfun(@(j) ... find(any(matches(:, matches(j,:)),2)), 1:size(A,1), 'UniformOutput', false); 

This alternative may be faster if you have short lines, i.e. when size(A,2) small:

 function answers = find_answers(A) % Returns an "answers" matrix like in Acorbe solution c = unique(A); answers = false(size(A,1), size(A,1)); idx = 1:size(A,1); for i = 1:numel(c) I = any(A == c(i), 2); uMatch = idx(I); answers(uMatch, uMatch) = true; isReady = all(A <= c(i), 2); if any(isReady), idx(isReady) = []; A = A(~isReady,:); end end 
+1
source

Depending on what you plan to do with this output, it may be redundant to have a match for "3rd line: line1".

You already have this match in your output in the form "1st line: line3"

0
source

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


All Articles