フィルターのクリア

bitget for array (count no. of bits)

19 ビュー (過去 30 日間)
Aravin
Aravin 2012 年 8 月 7 日
回答済み: Oliver Woodford 2013 年 11 月 22 日
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.

採用された回答

Matt Fig
Matt Fig 2012 年 8 月 7 日
編集済み: Matt Fig 2012 年 8 月 8 日
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);
  8 件のコメント
Matt Fig
Matt Fig 2012 年 8 月 8 日
Note carefully that the algorithm Teja gave you will automatically return all bits. I understood you to want to specify the bits to sum up. Either way, whether you specify D or calculate it using
D = floor(log2(max(x(:)))) + 1;
you can simply use reshape like Teja did to work the algorithm on a matrix. As for the uint8 part, there is no need to change your actual matrix to double, just change the copy used by the algorithm. For example:
x = uint8(round(rand(10,20)*255)); % Your matrix: we preserve this.
S = double(x(:)); % Only temporary. Overwritten below.
D = floor(log2(max(S))) + 1; % Or specify D! (As you need.)
S = reshape(sum(rem(floor(bsxfun(@times,S,pow2(1-D:0))),2),2),size(x));
Aravin
Aravin 2012 年 8 月 8 日
Thanks Matt

サインインしてコメントする。

その他の回答 (1 件)

Oliver Woodford
Oliver Woodford 2013 年 11 月 22 日
I assume from your question that you actually want to do a vectorized bitcount, rather than a vectorized bitget. If that is correct then I suggest you use the bitcount submission on the File Exchange.

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by