How to generate all possible combinations of 0-1 matrix in Python?
<p>How can generate all possible combinations of a 0-1 matrix of size K by N?</p>

<p>For example, if I take K=2 and N=2, I get the following combinations.</p>

<pre><code>combination 1
[0, 0;
 0, 0]; 
combination 2
[1, 0;
 0, 0]; 
combination 3
[0, 1;
 0, 0]; 
combination 4
[0, 0;
 1, 0]; 
combination 5
[0, 0;
 0, 1]; 
combination 6
[1, 1;
 0, 0]; 
combination 7
[1, 0;
 1, 0]; 
combination 8
[1, 0;
 0, 1]; 
combination 9
[0, 1;
 1, 0]; 
combination 10
[0, 1;
 0, 1]; 
combination 11
[0, 0;
 1, 1]; 
combination 12
[1, 1;
 1, 0]; 
combination 13
[0, 1;
 1, 1]; 
combination 14
[1, 0;
 1, 1]; 
combination 15
[1, 1;
 0, 1]; 
combination 16
[1, 1;
 1, 1]; 
</code></pre>

<p>A one-liner solution with <code>numpy</code> and <code>itertools</code>:</p>

<pre><code>[np.reshape(np.array(i), (K, N)) for i in itertools.product([0, 1], repeat = K*N)]
</code></pre>

<p><em>Explanation:</em> the <code>product</code> function returns a Cartesian product of its input. For instance, <code>product([0, 1], [0, 1])</code> returns an iterator that comprises all possible permutations of <code>[0, 1]</code> and <code>[0, 1]</code>. In other words, drawing from a product iterator:</p>

<pre><code>for i, j in product([0, 1], [0, 1]):
</code></pre>

<p>is actually equivalent to running two nested for-loops:</p>

<pre><code>for i in [0, 1]:
    for j in [0, 1]:
</code></pre>

<p>The for-loops above already solve the problem at hand for a specific case of <code>K, N = (1, 0)</code>. Continuing the above line of thought, to generate all possible zero/one states of a vector <code>i</code>, we need to draw samples from an iterator that is equivalent to a nested for-loop of depth <code>l</code>, where <code>l = len(i)</code>. Luckily, <code>itertools</code> provides the framework to do just that with its <code>repeat</code> keyword argument. In the case of OP's problem this permutation depth should be <code>K*N</code>, so that it can be reshaped into a numpy array of proper sizes during each step of the list comprehension.</p>

python combinations