鉴于MATLAB uint32被解释为一个位串,什么是一种有效和简洁的方法来计算字符串中有多少非零位?
我有一个工作,天真的方法循环比特,但这对我的需求来说太慢了.(使用std :: bitset count()的C++实现几乎立即运行).
我找到了一个非常好的页面列出了各种位计数技术,但我希望有一种简单的MATLAB方式.
http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetNaive
更新#1
刚刚实现了Brian Kernighan算法,如下所示:
w = 0;
while ( bits > 0 )
bits = bitand( bits, bits-1 );
w = w + 1;
end
Run Code Online (Sandbox Code Playgroud)
性能仍然很糟糕,超过10秒钟只计算4096 ^ 2重量计算.使用std :: bitset中的count()的我的C++代码在亚秒时间内执行此操作.
更新#2
这是我迄今为止尝试过的技术的运行时间表.我会在获得更多想法/建议时更新它.
矢量化Scheiner算法=> 2.243511秒 矢量化朴素bitget loop => 7.553345秒 Kernighan算法=> 17.154692秒 length(find(bitget(val,1:32)))=> 67.368278秒 nnz(bitget(val,1:32))=> 349.620259秒 Justin Scheiner的算法,展开循环=> 370.846031秒 Justin Scheiner的算法=> 398.786320秒 天真的比特环= = 456.016731秒 sum(dec2bin(val)=='1')=> 1069.851993秒
注释:MATLAB中的dec2bin()函数似乎执行得很差.它运行得非常慢.
注释:"Naive bitget loop"算法实现如下:
w=0;
for i=1:32
if bitget( val, i ) == 1
w = …Run Code Online (Sandbox Code Playgroud) 我正在读取位图文件并将每个 RGB值从0到255转换为二进制.
因此240 x 320位图将具有230400个RGB值进行转换.原来的dec2bin函数太慢了,所以我写了自己的函数,因为我知道我的值总是在0到255之间.
但是,通过230400值仍将需要大约.在我的机器上6秒,单色位图大约需要2.3秒.
无论如何,加速到1秒甚至更好的0.5秒,因为我的应用程序每msec计数?
这是我的代码:
function s = dec2bin_2(input)
if input == 255
s = [1;1;1;1;1;1;1;1];
return;
end
s = [0;0;0;0;0;0;0;0];
if input == 0
return;
end
if input >= 128
input = input - 128;
s(1) = 1;
if input == 0
return;
end
end
if input >= 64
input = input - 64;
s(2) = 1;
if input == 0
return;
end
end
if input >= 32
input = input - 32;
s(3) = …Run Code Online (Sandbox Code Playgroud)