bitcount
Version 1.0.2 (2 ko) par
Matlab Pro
Count the number of set bits in each element. Time and memory efficient
bitcount Counts the number of set bits in each element
Usage:
B = bitcount(A)
Counts the number '1' bits in each element
B = bitcount(A, bitValue)
"bitValue" = 1 = default = counts the occurance of '1'
if bitValue = 0; counts the number '0'
The total bits to verify is [8,16,32,or 64] based on the maximal value of A
B = bitcount(A, bitValue, maxBits)
the total # of bits to examine
The "bitcount" I have implemented here - is much more time/memory efficient vs the Ref above
Efficiency evaluation test: x 10:
maxData = 1e4;
data = uint32(randi([1,intmax('uint32')],1,maxData));
tic;cell2mat(arrayfun(@(x) sum(bitget(x,1:32)),data,'UniformOutput',false)');t_elapsed1 = toc;
tic;bitcount(data);t_elapsed2 = toc;
eff = t_elapsed1 / t_elapsed2;
maxData = 1e4: eff = 10
maxData = 1e5: eff = 20
maxData = 5e5: eff = 40
maxData = 1e6: eff = 56
maxData = 1e7: eff = 128
Examples:
data = 0:15;
out = bitcount(data);
bin_representation = cellfun(@(x) dec2bin(x,4),num2cell(data),'uni',0)';
nBits = num2cell(out)';
disp([num2cell(data(:)), bin_representation, nBits])
% Counts the #'0', default # of bits to examine = 8
data = 0:15;
out = bitcount(data,0); % out = [8 7 7 6 7 6 6 5 7 6 6 5 6 5 5 4]
% Counts the #'0', # of bits to examine = 4
data = 0:15;
out = bitcount(data,0,4); % out = [4 3 3 2 3 2 2 1 3 2 2 1 2 1 1 0]
Created by Noah Safra May 2025
Citation pour cette source
Matlab Pro (2026). bitcount (https://fr.mathworks.com/matlabcentral/fileexchange/180507-bitcount), MATLAB Central File Exchange. Extrait(e) le .
Compatibilité avec les versions de MATLAB
Créé avec
R2024b
Compatible avec toutes les versions
Plateformes compatibles
Windows macOS LinuxTags
Remerciements
Inspiré par : Bitcount & bitwise hamming distance
Découvrir Live Editor
Créez des scripts avec du code, des résultats et du texte formaté dans un même document exécutable.
| Version | Publié le | Notes de version | |
|---|---|---|---|
| 1.0.2 | Improved interface |
||
| 1.0.1 | Now enabling also '0' count |
||
| 1.0.0 |
