我有一张矩阵:
1 2 3
4 5 6
7 8 1
我如何使用matlab找到它:
第一行:第3行 第二排:--- 第3行:row1
我希望每行的行索引都有共同的元素。
答案 0 :(得分:4)
考虑一下
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
矩阵是对称的,因为你的关系是。
答案 1 :(得分:1)
如果您有许多行和/或长行,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
答案 2 :(得分:0)
根据您计划对此输出执行的操作,对于&#34;第3行匹配可能是多余的:第1行和第34行。
您已在输出中以#34;第1行:第3行和第34行的形式获得此匹配;