Gwen Wong
Gwen Wong

Reputation: 357

How to traverse two same size matrices and compare them

I have two matrices filled with 0s and 1s

e.g.
A = [ 0 0 1 0,
      1 0 1 0 ]

B = [ 1 1 1 1
      0 0 0 0 ]

and I'd like to compared the values form the same position against each other and return a 2x2 matrice

R = [ TP(1) FN(3)
      FP(2) TN(2) ]

TP = returns the amount of times A has the value 1, and B has the value 1
FN = returns the amount of times A has the value 0, and B has the value 1
FP = returns the amount of times A has the value 1, and B has the value 0
TN = returns the amount of times A has the value 0, and B has the value 0

How do i get each individual number in A and B?

Upvotes: 2

Views: 62

Answers (2)

Divakar
Divakar

Reputation: 221564

Approach #1: Comparison based using bsxfun -

pA = [1 0 1 0] %// pattern for A
pB = [1 1 0 0] %// pattern for B

%// Find matches for A against pattern-A and pattern-B for B using bsxfun(@eq.
%// Then, perform AND for detecting combined matches
matches = bsxfun(@eq,A(:),pA) & bsxfun(@eq,B(:),pB)

%// Sum up the matches to give us the desired counts
R = reshape(sum(matches),2,[]).'

Output -

R =
     1     3
     2     2

Approach #2: Finding decimal numbers -

Step-1: Find decimal numbers corresponding to the combined A's and B's

>> dec_nums = histc(bin2dec(num2str([B(:) A(:)],'%1d')),0:3)
dec_nums =
     2
     2
     3
     1

Step-2: Re-order the decimal numbers such that they line up as needed in the problem

>> R = reshape(flipud(dec_nums),2,[])'
R =
     1     3
     2     2

Upvotes: 2

Luis Mendo
Luis Mendo

Reputation: 112679

Use logical operators & and ~ applied on the linearized versions of A and B, and then nnz (or sum) to count the true values:

R = [nnz(A(:)&B(:)) nnz(~A(:)&B(:)); nnz(A(:)&~B(:)) nnz(~A(:)&~B(:))];

Upvotes: 2

Related Questions