Search code examples
matlabhammingweight

Matlab: index array by Hamming Weights


a contains indices and their occurrences. Now the indexing needs to be changed with Hamming weight so that indices with equal hamming weight will be summed up. How to do the Hamming weight indexing? Any ready command for this in Matlab?

>> a=[1,2;2,3;5,2;10,1;12,2]

     1     2
     2     3
     5     2
    10     1
    12     2
    13     8


>> dec2bin(a(:,1))

ans =

0001
0010
0101
1010
1100
1101

Goal: index things by Hamming weight

HW    Count
1     5 (=2+3)
2     5 (=2+1+2)
3     8 (=8)

Solution

  • You can do it as follows:

    a = [1,2;2,3;5,2;10,1;12,2;13,8]
    

    the following line needs to be added, to consider also a hammingweight of zero:

    if nnz(a(:,1)) == numel(a(:,1)); a = [0,0;a]; end
    % or just
    a = [0,0;a];   %// wouldn't change the result
    

    to get the indices

    rowidx = sum( de2bi(a(:,1)), 2 )
    

    to get the sums

    sums = accumarray( rowidx+1, a(:,2) ) %// +1 to consider Hammingweight of zero
    

    to get the Hammingweight vector

    HW = unique(rowidx)
    

    returns:

    rowidx =
    
         1
         1
         2
         2
         2
         3
    
    
    sums =
    
         5
         5
         8
    

    and all together:

    result = [HW, sums]
    %or
    result = [unique(rowidx), accumarray(rowidx+1,a(:,2))]
    
    result =
    
         0     0
         1     5
         2     5
         3     8
    

    If you are bothered by the 0 0 line, filter it out

    result(sum(result,2)>0,:)
    

    The result for a = [0,2;2,3;5,2;10,1;12,2;13,8] would be:

    result =
    
         0     2
         1     3
         2     5
         3     8