MATLAB: To determine the number of distinct pairs of value(s) in each column of matrix.

#condtionmatrix

Given that i have a 4 by N matrix, each entry of the matrix can take a random value from 1-6,
A = randi([1,6],[N 4])
I want to determine how many column(s) of the matrix have 2 distinct pairs of any two numbers from 1-6, for example [1;5;5;1] or [6;6;1;1]
First off, i want to start simply by checking say if the first column of A has 2 '1's and 2 '2's so we want to see if the column is the same as any of { [1;1;2;2;] , [1;2;1;2] , [1;2;2;1] …. }
I think you can do it like this:
valCount = hist( B(:,1) , uniqueVals )'==[2;2;0;0;0;0]
Then i want to generalise this so it can check every possible pairs of values and spit out the number of columns with two distinct pairs of numbers, but i have not a clue how to proceed.
Please if someone could kindly help

Best Answer

You could do the following. First find rows where there is only one other element equal to the element in the first column
idx = find(sum( A(:,1)==A,2 )==2);
Then make a new array B from rows satisfying the first condition and separate two values that didnt equal the first column. Then find indices where the remaining pairs are equal:
B = A(idx,:).'; % temporarily transposing to facilitate the reshaping step
remPairs = reshape(B(B~=B(1,:)),2,[]).';
idx2 = remPairs(:,1)==remPairs(:,2); % index where remaining pairs are equal
A(idx(idx2),:)
Related Question