我有一个矩阵:
1 2 3
4 5 6
7 8 1
我如何使用 matlab 找到这个:
第 1 行:第 3 行
第 2 行:---
第 3 行:第 1 行
我想为每一行都有行索引,女巫有共同的元素。
考虑这个
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
这里的输出是
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
当然answers
矩阵是对称的,因为你的关系是。
如果您有很多行和/或长行,Acorbe 提出的解决方案可能会很慢。我已经检查过,在大多数情况下,我在下面介绍的两种解决方案应该快得多。如果您的矩阵只包含几个不同的值(相对于矩阵的大小),那么这应该会很快工作:
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);
当您的行数较短时,即当行size(A,2)
数较小时,另一种选择可能会更快:
function answers = find_answers(A)
% Returns an "answers" matrix like in Acorbe's 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
根据您计划对此输出执行的操作,匹配“第 3 行:第 1 行”可能是多余的。
您已经在输出中以“第一行:第 3 行”的形式进行了此匹配