I need to create a diagonal matrix in python from an X matrix which is repeated 3 times. In matlab I do it in the following way:
X=[1 2 3;
4 5 6;
7 8 9]
for i=1:1:3
Brep{i}=X;
end
Mdiag=blkdiag(Brep{:})
Mdiag =
1 2 3 0 0 0 0 0 0
4 5 6 0 0 0 0 0 0
7 8 9 0 0 0 0 0 0
0 0 0 1 2 3 0 0 0
0 0 0 4 5 6 0 0 0
0 0 0 7 8 9 0 0 0
0 0 0 0 0 0 1 2 3
0 0 0 0 0 0 4 5 6
0 0 0 0 0 0 7 8 9
But I don't know how to do this in Pyhton.
I would appreciate any help.
--------------------------------- ANSWER:--------------------------------------
Taking into account the answer provided by Fabrizio Bernini, I modified his code in order to do it more general. The code can now repeat the matrix X (any dimension), n times on the diagonal. For example:
import numpy as np
n=5
x = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
Mdiag = np.zeros((n*x.shape[0], n*x.shape[1]))
for i in range(n):
Mdiag[x.shape[0]*i:x.shape[0]*i+x.shape[0],x.shape[1]*i:x.shape[1]*i+x.shape[1]]= x
Mdiag =[1., 2., 3., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[4., 5., 6., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[7., 8., 9., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 1., 2., 3., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 4., 5., 6., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 7., 8., 9., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 1., 2., 3., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 4., 5., 6., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 7., 8., 9., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 2., 3., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 4., 5., 6., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 7., 8., 9., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 2., 3.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 4., 5., 6.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 7., 8., 9.]
Thanks you all for the answers provided.