简体   繁体   English

比较矩阵每一行中的元素并计算相似值

[英]Comparing elements in each row of a matrix and count the similar values

I have a matrix like this: 我有一个像这样的矩阵:

 line=[1 3 5 0 0 4 2; 
       1 3 8 0 8 2 2 ] 

I want to compare the rows in this matrix. 我想比较此矩阵中的行。 If the 1st column of the first row is the same as 1st column of second row then increase a counter. 如果第一行的第一列与第二行的第一列相同,则增加一个计数器。 But if the value is zero, then the counter should not be increased. 但是,如果该值为零,则不应增加计数器。

For the example above I expect the output to be match = 3 where the matching values are 1,3,2 so the match = 3 对于上面的示例,我希望输出为match = 3,其中匹配值为1,3,2,因此match = 3

I would go for this: 我会为此:

match = sum((line(1, :) == line(2, :)) & (line(1, :) != 0))

The Array comparison line(1, :) == line(2, :) will give you (logical) 1 at the points, where both rows have identical values: 数组比较 line(1, :) == line(2, :)在两行具有相同值的点上将为您(逻辑) 1

ans =
  1  1  0  1  0  0  1

Next, you need to exclude possible 0 values. 接下来,您需要排除可能的0值。 That can be done by findind non-zero elements just in the first row ( line(1, :) != 0 ), and then using the & operator on the results. 可以通过仅在第一行中找到findind非零元素( line(1, :) != 0 ),然后对结果使用&运算符。 You'll get: 你会得到:

ans =
  1  1  0  0  0  0  1

At last, you just have to count the ones using sum . 最后,您只需要使用sum来计数。

You can check if the sum of each column divided by the first line equal 2. 您可以检查每一列的总和除以第一行是否等于2。

So: 所以:

count = sum(sum(x)./x(1,:)==2)

Since 0/0 is indetermined, 0 will not be taken into account. 由于0/0是不确定的,因此不会考虑0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM