What's the most efficient way to convert a vector into a triangular matrix?

For example, I want to convert torch.tensor([1,2,3,4,5,6] to torch.tensor([[1,0,0],[2,3,0],[4,5,6]]), what is the most efficient way to do the conversion?

2 Likes

Currently, take tril_indices from numpy, and use advanced indices to assign to an all zeros matrix.

1 Like

Beside numpy, PyTorch has now implemented tril_indices.

x = torch.tensor([1., 2., 3., 4., 5., 6.])
m = torch.zeros((3, 3))

tril_indices = torch.tril_indices(row=3, col=3, offset=0)
m[tril_indices[0], tril_indices[1]] = x
5 Likes