HighwayJohn - 1 year ago 57

Python Question

I have the following problem. I want to create a numpy-matrix of size 2^L x L+2. In the first column are variables, which I define later in the program. In the last L columns should be all possibilities to distribute zeroes and ones (In my opinion binary counting could be an option, see example) In the second column are the number of ones. I need this column to sort the matrix afterwards for the second column.

`[[ x1, 0, 0, 0, 0]`

[ x2, 1, 0, 0, 1]

[ x3, 1, 0, 1, 0]

[ x4, 2, 0, 1, 1]

[ x5, 1, 1, 0, 0]

[ x6, 2, 1, 0, 1]

[ x7, 2, 1, 1, 0]

[ x8, 3, 1, 1, 1]]

Answer

What you're asking for seems unlikely to be what you really need in order to solve whatever problem you're having. That said, it's easy enough to generate the RHS by taking advantage of numpy's broadcasting abilities:

```
>>> L = 3
>>> m = (np.arange(2**L)[:,None] >> np.arange(L)[::-1]) & 1
>>> m
array([[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1]], dtype=int32)
>>> np.hstack([m.sum(1,keepdims=True), m])
array([[0, 0, 0, 0],
[1, 0, 0, 1],
[1, 0, 1, 0],
[2, 0, 1, 1],
[1, 1, 0, 0],
[2, 1, 0, 1],
[2, 1, 1, 0],
[3, 1, 1, 1]], dtype=int32)
```

You can insert your column of data in similar fashion.