私はマトリックスを持っています:
1 2 3
4 5 6
7 8 1
これを見つけるためにmatlabを使用するにはどうすればよいですか:
1 行目: row3
2 行目: ---
3 行目: row1
各行ウィッチの行インデックスに共通の要素を持たせたいと考えています。
このことを考慮
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 が提案するソリューションは非常に遅くなる可能性があります。ほとんどの場合、以下に示す 2 つのソリューションがかなり高速であることを確認しました。マトリックスに (マトリックスのサイズに比べて) 異なる値がほとんど含まれていない場合、これは非常に高速に機能するはずです。
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」に一致させるのは冗長になる可能性があります。
この一致は、出力の早い段階で「1 行目: 行 3」の形式で既に存在します。