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.
Just loop over all integers in
[0,2^n), and print the number as binary. If you always want to havendigits (e.g. insert leading zeros), this would look like:Edit: there are a number of ways to put the results in a matrix. The easiest is to use
which will produce an
n-by-2^nmatrix of typechar. Each row is one of the bit strings.If you really want to store strings in each row, you can do this:
However, if you’re looking for efficient processing, you should remember that integers are already stored in memory in binary! So, the vector:
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.