Calculating Hamming weight efficiently in matlab

后端 未结 9 1528
你的背包
你的背包 2020-12-09 11:46

Given a MATLAB uint32 to be interpreted as a bit string, what is an efficient and concise way of counting how many nonzero bits are in the string?

I have a working

9条回答
  •  悲&欢浪女
    2020-12-09 12:14

    EDIT: NEW SOLUTION

    It appears that you want to repeat the calculation for every element in a 4096-by-4096 array of UINT32 values. If this is what you are doing, I think the fastest way to do it in MATLAB is to use the fact that BITGET is designed to operate on matrices of values. The code would look like this:

    numArray = ...your 4096-by-4096 matrix of uint32 values...
    w = zeros(4096,4096,'uint32');
    for iBit = 1:32,
      w = w+bitget(numArray,iBit);
    end
    

    If you want to make vectorized versions of some of the other algorithms, I believe BITAND is also designed to operate on matrices.


    The old solution...

    The easiest way I can think of is to use the DEC2BIN function, which gives you the binary representation (as a string) of a non-negative integer:

    w = sum(dec2bin(num) == '1');  % Sums up the ones in the string
    

    It's slow, but it's easy. =)

提交回复
热议问题