Multiply each scalar in matrix A with tensor B

Suppose I have a matrix e.g. A = tensor([[0, 1, 2], [3, 4, 5]]) , and I have another tensor B e.g. B = torch.tensor([1, 5, 2, 4]), how can I multiply each scalar in A with B, to get C of shape [2, 3, 4] in this example?

Hi Bob!

I believe you are asking for the generalized outer product. Please
try torch.ger() (torch.outer) with .reshape() or torch.einsum:

ABa = torch.ger (A.reshape([6]), B).rehshape ([2, 3, 4])
ABb = torch.einsum ('ij, k -> ijk', A, B)

These two versions should give you the same result. Do they do what
you want?

Best.

K. Frank

1 Like

Wow! Thanks a lot, works like charm~