Given a positive integer n, I want to generate all possible n bit combinations in matlab.
For ex : If n=3, then answer should be
000
001
010
011
100
101
110
111
How do I do it ? I want to actually store them in matrix. I tried
for n=1:2^4
r(n)=dec2bin(n,5);
end;
but that gave error "In an assignment A(:) = B, the number of elements in A and B must be the same.
They are strings consisting either 0 or 1 as each letter. They can also be seen as binary numbers in mathematics. They can also have variable length.
Approach: For any digit length N, there will be 2N binary numbers.
' wildcard characters, generate all binary strings that can be formed by replacing each wildcard character by '0' or '1'. We pass index of next character to the recursive function. If the current character is a wildcard character '? ', we replace it with '0' or '1' and do the same for all remaining characters.
Answer and Explanation: A bit string of length 4 would have all the binary numbers between, 0000 and 1111 . There can be no other permutations or arrangements of the digits that can contain consecutive 1s. Hence there must be 10 bit-strings of length 4 which do not have consecutive 1s.
Just loop over all integers in [0,2^n)
, and print the number as binary. If you always want to have n
digits (e.g. insert leading zeros), this would look like:
for ii=0:2^n-1,
fprintf('%0*s\n', n, dec2bin(ii));
end
Edit: there are a number of ways to put the results in a matrix. The easiest is to use
x = dec2bin(0:2^n-1);
which will produce an n
-by-2^n
matrix of type char
. Each row is one of the bit strings.
If you really want to store strings in each row, you can do this:
x = cell(1, 2^n);
for ii=0:2^n-1,
x{ii} = dec2bin(ii);
end
However, if you're looking for efficient processing, you should remember that integers are already stored in memory in binary! So, the vector:
x = 0 : 2^n-1;
Contains the binary patterns in the most memory efficient and CPU efficient way possible. The only trade-off is that you will not be able to represent patterns with more than 32 of 64 bits using this compact representation.
This is a one-line answer to the question which gives you a double array of all 2^n
bit combinations:
bitCombs = dec2bin(0:2^n-1) - '0'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With