1

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)
hhh
  • 50,788
  • 62
  • 179
  • 282
  • ERR...I realised an easier solution to original prob, just use HW over the whole initial vector like here http://stackoverflow.com/a/9397290/164148 and then just `hist(HW)`. Thank you for your input anyway, the simplest solution rocks. – hhh Apr 07 '14 at 10:08

2 Answers2

2

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
Robert Seifert
  • 25,078
  • 11
  • 68
  • 113
1

Try this -

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

HW = dec2bin(a(:,1)) - '0'; 

out = accumarray(sum(HW,2), a(:,2), [], @sum);%%// You don't need that "sum" option it seems, as that's the default operation with accumarray

final_out = [unique(sum(HW,2)) out]

Output -

a =

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


final_out =

     1     5
     2     5
     3     8
Divakar
  • 218,885
  • 19
  • 262
  • 358