MATLAB: Bitget for array (count no. of bits)

array bit countarray bit getbit countbitgetMATLAB

Hi everyone,
How to take bitget of an array. Let say:
a = 7;
s = sum(bitget(a,1:8));
will return 3 as there are three bits on in number 7. If I have any array
a = [1 2 7 6];
then how can I do the similar bit count operation for each element in a.

Best Answer

ARRAYFUN might be useful here.
arrayfun(@(x) sum(bitget(x,1:8)),[1 2 7 6])
This is much faster for larger row vectors. D is the number of bits (8 in the above formula):
sum(rem(floor(bsxfun(@times,x',pow2(1-D:0))),2),2);