2012-10-27 55 views

回答

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矩陣是對稱的,因爲你的關係是。

+0

不起作用...?索引超過矩陣尺寸。 –

+0

先試試你的方陣。它會工作。可能它只是行列大小的問題(在方陣中相等)。我會盡快解決。 – Acorbe

+0

請幫忙。我仍然在等待:( –

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