Hello, say I have
A = torch.rand(vec_len,1)
B = torch.rand(vec_len,1)
C = torch.rand(vec_len,1)
and I want to create a tensor T
, the shape of which is (vec_len,3,3)
and its i_th
channel would be like this:
[[Ai, 0, 0],
[0, 0, Bi],
[0, Ci, 0]]
How can I fast create such a tensor? Thanks!
thecho7
(Suho Cho)
January 16, 2022, 11:03am
2
vec_len = 5
a = torch.rand(vec_len, 1)
b = torch.rand(vec_len, 1)
c = torch.rand(vec_len, 1)
aa = torch.tile(a, (1, 3))
bb = torch.tile(b, (1, 3))
cc = torch.tile(c, (1, 3))
index_tensor = torch.Tensor([[1, 0, 0], [0, 0, 1], [0, 1, 0]])
index_tensor_ = torch.tile(index_tensor.view(-1, 3, 3), (vec_len, 1, 1))
stacked = torch.stack((aa, bb, cc), dim=2).type(torch.double)
result = torch.where(index_tensor_ > 0, stacked, 0.)
This is the best among what I know
Any idea?
@WoodezXJ @thecho7
vec_len = 5
A = torch.rand(vec_len)
B = torch.rand(vec_len)
C = torch.rand(vec_len)
final = torch.zeros(vec_len, 3, 3)
final[:, 0, 0] = A
final[:, 1, 2] = B
final[:, 2, 1] = C
final
Thanks, guess replacing the entry of a zero tensor might be the fastest way…