Count equal values in multiple matrices

조회 수: 2 (최근 30일)
Christopher
Christopher 2014년 9월 30일
댓글: Image Analyst 2014년 9월 30일
I have a number of M by N matrices with random integers between 1 and 5, for example if I have:
X1 = [1 2 1 3 5 4 2 4 3; 5 3 3 2 5 4 3 2 3; 3 3 2 4 5 3 2 4 1; 4 5 3 4 1 4 2 3 1;]
X2 = [5 4 4 3 5 1 2 3 1; 5 3 2 4 2 3 1 4 3; 4 2 3 3 4 1 3 5 2; 1 3 1 3 4 5 3 2 4;]
The answer is
X2 = [1 1 1 2 2 1 2 1 1; 2 2 1 1 1 1 1 1 2; 1 1 1 1 1 1 1 1 1; 1 1 1 1 1 1 1 1 1;]
However, my real matrix is much larger and I have >>2 matrices to compare. What is a fast vectorized way to perform this operation?
  댓글 수: 1
Image Analyst
Image Analyst 2014년 9월 30일
What if you have
X1 = [1 2 1 3 5 4 2 4 3; 5 3 3 2 5 4 3 2 3; 3 3 2 4 5 3 2 4 1; 4 5 3 4 1 4 2 3 1;]
X2 = [5 4 4 3 5 1 2 3 1; 5 3 2 4 2 3 1 4 3; 4 2 3 3 4 1 3 5 2; 1 3 1 3 4 5 3 2 4;]
X3 = [1 2 1 9 1 4 2 4 3; 5 3 3 2 5 4 3 2 3; 3 3 2 4 5 3 2 4 1; 4 5 3 4 1 4 2 3 1;]
X4 = [5 4 4 9 1 1 2 3 1; 5 3 2 4 2 3 1 4 3; 4 2 3 3 4 1 3 5 2; 1 3 1 3 4 5 3 2 4;]
Look at the 4th column - we have a pair of 3's and a pair of 9's. And in the 5th column, a pair of 1's. So in the output would it now be 4? In the extreme, you could just take a histogram of every element across the X arrays. The histogram will have 1's in non-repeated bins and 2, 3, 23, or whatever in bins that are repeated for some number. What do you want to do in that case?

댓글을 달려면 로그인하십시오.

답변 (2개)

Michael Haderlein
Michael Haderlein 2014년 9월 30일
I guess you don't want to overwrite X2. Introducing X3, the easiest way is:
X3 = 1+(X1==X2);
  댓글 수: 2
Christopher
Christopher 2014년 9월 30일
편집: Christopher 2014년 9월 30일
What if I have many matrices? Should I write
Y = 1+(X1==X2)+(X1==X3)+(X1==X4)+(X1==X5)+(X1==X6)+(X1==X7)+(X1==X8)+(X1==X9)+(X1==X10)+(X1==X11)+(X1==X12)+(X1==X13)+(X1==X14)+(X1==X15)+(X1==X16)+(X1==X17)+(X1==X18)
Or is there a faster way to do this? All the matrices are the same size. Thanks.
Sean de Wolski
Sean de Wolski 2014년 9월 30일
You should avoid creating matrices like that:

댓글을 달려면 로그인하십시오.


Iain
Iain 2014년 9월 30일
If you can concatenate your matrices in the 3rd dimension:
x_oth = X2;
x_oth(:,:,2) = X3;
...
Then you may be able to use
Y =1+ sum(bsxfun(@eq,X1,x_oth),3);

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by