Search code examples
octavehammingweight

How to calculate the Hamming weight for a vector?


I am trying to calculate the Hamming weight of a vector in 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.


Solution

  • 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:

    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.

    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.

    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.