I have a set of 32 bits binary values incoming from a sensor. I have to form all the possible combinations of these values and then convert them into a decimal value.
The code slows down terribly if the incoming rows are more that 80000 - 90000. It takes 120 minutes to run.
I want to optimize this code, since 3 For loops and a function within the innermost loop is slowing down my algorithm. Is there any chance that I can eliminate some For loops and substitute them with vectorizing to speed up the process.
b1 = [0 1 0 1 0 1 1 1 1 1 1 1 1 1 0 1 0 0 1 0 1 0 0 0 0 1 0 0 1 0 0 1];
b2 = [0 1 0 1 0 1 1 1 1 1 1 0 1 1 0 1 0 0 1 0 1 0 0 0 0 1 0 0 1 0 0 1];
b3 = [0 1 0 1 0 1 0 1 1 1 0 1 1 1 0 1 0 0 1 0 1 0 0 1 0 1 0 0 1 0 0 1];
b4 = [0 1 0 1 0 1 1 1 1 1 0 1 1 0 0 1 0 0 1 0 1 0 0 0 0 1 0 0 1 0 0 1];
b5 = [0 1 0 1 1 1 1 0 1 1 0 1 1 1 0 1 1 0 1 0 1 0 0 1 0 1 0 0 1 0 0 1];
FullVector = [b1;b2;b3;b4;b5];
for Idx = 1:size(FullVector,1)
k = 1;
MinLength = 4;
MaxLength = 8;
StepSize = 2;
for StartByte = 1:8
for StartBit = 1:8
for SignalLength = MinLength:StepSize:MaxLength
DecimalVals.s(Idx,k) = BitCombinations(FullVector,StartByte,StartBit,SignalLength);
k = k+1;
end
end
end
end
The function:
function decimal = BitCombinations(ByteArray,Sbyte,Sbit,lengthSignal)
%function extracts the required bits from a byte array and
%returns the decimal equivalent of the bits.
%Inputs:
%Sbyte - Starting byte
%Sbit - Starting bit in the given byte
%length - length of bits to be extracted
%Output:
%dec - Returns the dec
startbit_pos = ((Sbyte-1)*8+Sbit);
endbit_pos = ((Sbyte-1)*8+Sbit+lengthSignal-1);
if endbit_pos <= 64
extractedbits = ByteArray(startbit_pos:endbit_pos);
extractedbits = fliplr(extractedbits);
decimal = bi2de(extractedbits);
else
decimal = NaN;
end
end
Idxis not incremented, for example. And can valid symbols cross byte arrays? (your code seems to allow this)Idxand everything seems to be working.... = BitCombinations(FullVector(k, :), ...? Second, theb's are 32 bits long, while you check if theendbit_posis<64. Shouldn't it be<32in that case?