Happy Mittal
Happy Mittal

Reputation: 3747

How to generate all possible combinations n-bit strings?

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.

Upvotes: 5

Views: 16173

Answers (3)

theOne
theOne

Reputation: 471

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'

Upvotes: 1

André Caron
André Caron

Reputation: 45224

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.

Upvotes: 9

Subs
Subs

Reputation: 529

So many ways to do this permutation. If you are looking to implement with an array counter: set an array of counters going from 0 to 1 for each of the three positions (2^0,2^1,2^2). Let the starting number be 000 (stored in an array). Use the counter and increment its 1st place (2^0). The number will be 001. Reset the counter at position (2^0) and increase counter at 2^1 and go on a loop till you complete all the counters.

Upvotes: 0

Related Questions