如何遍历两个相同大小的矩阵并进行比较

时间:2014-12-06 18:52:31

标签: matlab for-loop matrix

我有两个填充0和1的矩阵

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

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

我希望将相同位置的值相互比较并返回2x2矩阵

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

如何获得A和B中的每个个人号码?

2 个答案:

答案 0 :(得分:2)

方法#1:使用 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,[]).'

输出 -

R =
     1     3
     2     2

方法#2:查找十进制数 -

步骤1:查找与合并的AB'

相对应的十进制数字
>> dec_nums = histc(bin2dec(num2str([B(:) A(:)],'%1d')),0:3)
dec_nums =
     2
     2
     3
     1

步骤2:重新排序小数,使它们在问题中根据需要排列

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

答案 1 :(得分:2)

&~的{​​{3}}版本上使用logical operators AB,然后linearized(或nnz)计算true值:

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