Hamming weight for a list of integers in Matlab [duplicate]

情到浓时终转凉″ 提交于 2019-12-07 15:19:25

This is a little hacky, but it works:

res = sum( dec2bin(a).' == '1' );

It converts a to binary representation, looks at how many characters in that representation are '1', and sums up those numbers.

Richard Z
#% Quickly for a few or quickly for millions?
#% A quick method for a 32 bit int requires a 16 bit look-up table
#% Ideally the table is created once and passed to the function for usage
#% vectorized
vt=randi(2^32,[4096*4096,1])-1; #% input vector vt

num_ones=uint8(zeros(65536,1));
for i=0:65535
 num_ones(i+1)=length( find( bitget( i, 1:32 ) ) ) ;
end % 0.43 sec to create table

v=num_ones(mod(vt,65536)+1)+num_ones(floor(vt/65536)+1); #% 0.85 sec
% dec2bin is 1000 times slower
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!