2014-03-26 102 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的信息。