views:

45

answers:

2

Here's the code I am using now, where decimal1 is an array of decimal values, and B is the number of bits in binary for each value:

for (i = 0:1:length(decimal1)-1)
    out = dec2binvec(decimal1(i+1),B);
    for (j = 0:B-1)
        bit_stream(B*i+j+1) = out(B-j);
    end
end

The code works, but it takes a long time if the length of the decimal array is large. Is there a more efficient way to do this?

A: 
bitstream = zeros(nelem * B,1);

for i = 1:nelem
    bitstream((i-1)*B+1:i*B) = fliplr(dec2binvec(decimal1(i),B));
end

I think that should be correct and a lot faster (hope so :) ).

edit:

I think your main problem is that you probably don't preallocate the bit_stream matrix.

I tested both codes for speed and I see that yours is faster than mine (not very much tho), if we both preallocate bitstream, even though I (kinda) vectorized my code.

If we DONT preallocate the bitstream my code is A LOT faster. That happens because your code reallocates the matrix more often than mine.

So, if you know the B upfront, use your code, else use mine (of course both have to be modified a little bit to determine the length at runtime, which is no problem since dec2binvec can be called without the B parameter).

George B.
A: 

The function DEC2BINVEC from the Data Acquisition Toolbox is very similar to the built-in function DEC2BIN, so some of the alternatives discussed in this question may be of use to you. Here's one option to try, using the function BITGET:

decimal1 = ...;  %# Your array of decimal values
B = ...;         %# The number of bits to get for each value
nValues = numel(decimal1);        %# Number of values in decimal1
bit_stream = zeros(1,nValues*B);  %# Initialize bit stream
for iBit = 1:B                    %# Loop over the bits
  bit_stream(iBit:B:end) = bitget(decimal1,B-iBit+1);  %# Get the bit values
end

This should give the same results as your sample code, but should be significantly faster.

gnovice