使用bsxfun计算匹配值二矩阵

时间:2013-03-24 06:04:48

标签: matlab matrix bsxfun

我使用c=bsxfun(@eq,b,a)来比较两个矩阵的值。但我觉得很难计算不匹配的数值。例如,我使用此代码

a = [1 2 3 4 7 6; ...
     3 2 4 6 7 2 ];
b = [1 3 2 4 5 7; ...
     3 4 5 6 7 2; ...
     2 3 4 5 6 6];
for i = 1:size(a,1)
    c= bsxfun(@eq,a(i,:),b)
    match = sum(c')
end

和结果

 c =
   1     0     0     1     0     0
   0     0     0     0     1     0
   0     0     0     0     0     1

 match =
   2     1     1

c =
   0     0     0     0     0     0
   1     0     0     1     1     1
   0     0     1     0     0     0

match =
   0     4     1

我想在第二场比赛中保存第一场比赛的价值。例如

total_match = 
   2 5 2

你有什么建议吗?感谢..

1 个答案:

答案 0 :(得分:0)

无需循环

match = bsxfun( @eq, permute( a, [1 3 2]), permute( b, [3 1 2] ) ); % result in 2x3x6 boolean
match = sum( match, 3 ); % sum matches across rows of a--b
total_match = sum( match, 1 ); 

PS
It is best not to use i and j as variable names in Matlab