简体   繁体   English

如何计算向量的汉明权重?

[英]How to calculate the Hamming weight for a vector?

I am trying to calculate the Hamming weight of a vector in Matlab. 我正在尝试在Matlab中计算向量的汉明权重。

function Hamming_weight (vet_dec)
Ham_Weight = sum(dec2bin(vet_dec) == '1')    
endfunction

The vector is: 向量是:

Hamming_weight ([208    15   217   252   128    35    50   252   209   120    97   140   235   220    32   251])

However, this gives the following result, which is not what I want: 但是,这给出了以下结果,这不是我想要的结果:

Ham_Weight =

   10   10    9    9    9    5    5    7

I would be very grateful if you could help me please. 如果您能帮助我,我将不胜感激。

You are summing over the wrong dimension! 您正在总结错误的维度!

sum(dec2bin(vet_dec) == '1',2).'
ans =
   3   4   5   6   1   3   3   6   4   4   3   3   6   5   1   7

dec2bin(vet_dec) creates a matrix like this: dec2bin(vet_dec)创建如下矩阵:

11010000
00001111
11011001
11111100
10000000
00100011
00110010
11111100
11010001
01111000
01100001
10001100
11101011
11011100
00100000
11111011

As you can see, you're interested in the sum of each row, not each column. 如您所见,您对每一行的总和而不是每一列的总和感兴趣。 Use the second input argument to sum(x, 2) , which specifies the dimension you want to sum along. 将第二个输入参数用于sum(x, 2) ,它指定要求和的维。

Note that this approach is horribly slow, as you can see from this question . 请注意,从这个问题可以看出,这种方法非常慢。

EDIT 编辑

For this to be a valid, and meaningful MATLAB function, you must change your function definition a bit. 为了使它成为有效且有意义的MATLAB函数,必须稍微更改函数定义。

function ham_weight = hamming_weight(vector)     % Return the variable ham_weight 

ham_weight = sum(dec2bin(vector) == '1', 2).';   % Don't transpose if 
                                                 % you want a column vector
end                                              % endfunction is not a MATLAB command.

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

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