Not sure exactly what you want to do here. But you can remove the for loop because in a weird way, you set the diagonal of a bunch of matrices to 1. You can do this with: z.diagonal(dim1=0, dim2=-1).fill_(1)