CarMoreno - 10 months ago 70

Python Question

I want to make a numpy array that looks like this:

`m = [1, 1, 1, 0, 0, 0, 0, 0, 0`

0, 0, 0, 1, 1, 1, 0, 0, 0

0, 0, 0, 0, 0, 0, 1, 1, 1]

I have seen this answer Make special diagonal matrix in Numpy and I have this:

`a = np.zeros(3,9)`

a[0, 0] = 1

a[0, 1] = 1

a[0, 2] = 1

a[1, 3] = 1

a[1, 4] = 1

a[1, 5] = 1

a[2, 6] = 1

a[2, 7] = 1

a[2, 8] = 1

But I want to use a 'for' cicle, How I can fill the diagonal efficiently?

Answer

One way is to simply stretch an identity array horizontally;

```
> np.repeat(np.identity(3, dtype=int), 3, axis=1)
array([[1, 1, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 1]])
```