2014-03-26 36 views
1

這個幾乎和這個一樣的問題Matrices intersection矩陣在matlab中的交集?

區別在於:如果所有矩陣的元素(i,j)的相交數是相同的數字,則不輸出-1,但輸出該數字。一個例子如下:

A1 = [2, 2, 0; 
     2, 2, 0; 
     0, 2, 0]; 


A2 = [2, 0, 4; 
     4, 3, 0; 
     0, 0, 1]; 


A3 = [2, 0, 0; 
     1, 0, 3; 
     3, 4, 3]; 

我想下面的矩陣:

B = [2, 2, 4; 
    -1, -1, 3; 
     3, -1, -1]; 
+2

我建議不要再次發佈該問題,特別是在幾天之內彼此。只需修改你的其他問題,使其更清楚你問的問題。 – MZimmerman6

+2

@ MZimmerman6:我不這麼認爲。修改已經回答的問題可能會讓後來閱讀的人感到困惑。 – Daniel

+1

如果只有A1和A2中的兩個對應元素是相同的,但A3中的元素是不同的。我們正在考慮這三個要素的「最大」?從你的'B'看來,這對我來說很重要。 – Divakar

回答

1

1版

out1 = -1.*(A1~=A2).*(A1~=A3).*(A2~=A3) 
max_mat = max(cat(3,A1,A2,A3),[],3) 
out1(~out1) = max_mat(~out1) 

輸出

out1 = 

    2  2  4 
    -1 -1  3 
    3 -1 -1 

版本2:也許更快的版本

假設 -如果出了三米的Elemen的在橫跨A1,A2和A3的相應位置TS,只有兩個是相同的,則取爲最終基質這三個要素的最大值,B.

代碼

%%// Concatenate all three A matrices 
A=cat(3,A1,A2,A3,A1); 

%%// Logical matrix with ones where all three elements are different from each other 
out1 = -1.*all(diff(A,[],3)~=0,3) 

%%// Get the max values, to be stored where -1 all three corresponding elements 
%%// are not different from each other 
max_mat = max(A,[],3) 

%%// Get the final output 
out1(~out1) = max_mat(~out1) 

這產生相同的輸出爲以前的版本。

3版

假設 -如果出在橫跨A1,A2和A3的相應位置的三個要素中,只有兩個是相同的,然後採取不同於其它兩個用於不同的元件最終的矩陣,B.

代碼

A=cat(3,A1,A2,A3,A1); 
AA = A(:,:,1:3); 
t1 = bsxfun(@ne,AA,mode(AA,3)); 
out1 = max(AA.*t1,[],3) + all(~t1,3).*A1; 
out1(all(diff(A,[],3)~=0,3))=-1; 

這產生相同的OUTP作爲以前的版本。

1
A1 = [2, 2, 0; 
     2, 2, 0; 
     0, 2, 0]; 


A2 = [2, 0, 4; 
     4, 3, 0; 
     0, 0, 1]; 


A3 = [2, 0, 0; 
     1, 0, 3; 
     3, 4, 3]; 
A=cat(3,A1,A2,A3); 

%identify all fields with identical values on the 3rd dimension 
[X,Y]=find(sum(abs(diff(A,1,3)),3)==0); 
%delete all but the first repetition, then use the previous code 
A(X,Y,2:end)=0; 

L=(sum(A~=0,3)>1); 

L*-1+(1-L).*sum(A,3) 

/更新:得到修復代碼,現在應該是正確的。

1

我會做這個

A = A1+A2+A3; 
B = (A1==A2)&(A1==A3); 
C = (A1==0)+(A2==0)+(A3==0); 

D = ones(3)*-1; 
D(B==1) = A1(B==1); 
D(C==2) = A(C==2); 
  • B記錄其數量同樣爲所有矩陣元素的位置。
  • C記錄元件的位置,其中兩個矩陣都爲0

然後,我們可以修改的D的元素,其值是設定最初-1,使用矩陣BC的信息。