Tensor: Is there a way to repeat each matrix element into diagonal submatrix?

Suppose I have a matrix tensor

a  b
c  d

and want to repeat it into

a 0 b 0
0 a 0 b
c 0 d 0
0 c 0 d

In numpy code, it is y = np.kron(x,np.eye(2)), I want to know pytorch equivalent.
My actual usage is higher than 2D, which has additional dimensions at the tail, though.
Thank you very much!

I don’t think it’s ready-mades, but starting with zeros and copying x into y[::2, ::2] and y[1::2, 1::2] should do the trick.
If your x isn’t tiny and the “stencil matrix” is reasonably small, a for foop over the stencil isn’t a performance headache.

Best regards


Hi Tom,
I’m operating on module parameters, will this copying & looping approach provide autograd support?
And how to use broadcasting semantics in the indexed assignment?


  1. Yes
  2. How would broadcasting look like?

P.S.: Please don’t ask the same question twice.

Sorry, I mis-interpreted the y[::2, ::2] syntax.