I have an integer array:
a=[3,4,5,6,7];
I want to convert it to a binary array with four bits each. For the above integer array I would lik
You can use the BITGET function:
abinary = [bitget(a,4); ... %# Get bit 4 for each number
bitget(a,3); ... %# Get bit 3 for each number
bitget(a,2); ... %# Get bit 2 for each number
bitget(a,1)]; %# Get bit 1 for each number
abinary = abinary(:)'; %'# Make it a 1-by-20 array
Matlab has the built-in function DEC2BIN. It creates a character array, but it's easy to turn that back to numbers.
%# create binary string - the 4 forces at least 4 bits
bstr = dec2bin([3,4,5,6,7],4)
%# convert back to numbers (reshape so that zeros are preserved)
out = str2num(reshape(bstr',[],1))'
A late answer I know, but MATLAB has a function to do this directly de2bi
out = de2bi([3,4,5,6,7], 4, 'left-msb');