Please help me explain the mechanism of this case of torch.matmul

Please help me explain the mechanism of this case of torch.matmul.
I can not understand why this case is this result.
Thank you very much!

import torch
# first argument 2D and second argument 1D
mat2_1 = torch.tensor([[1, 2, 3],
                       [4, 3, 8],
                       [1, 7, 2]])

mat2_2 = torch.tensor([3, 6, 2])

# assigning to output tensor
out_2 = torch.matmul(mat2_1, mat2_2)

print("\n2D-1D matmul :\n", out_2)

The output of above case is as follows

2D-1D matmul :
 tensor([21, 46, 49])

Hi @111466,

This is just standard matrix multiplication, in your case you have a 3x3 matrix that multiples with a 3x1 vector (both are represented as Tensors). When multiplying a 3x3 matrix with a 3x1 vector you get a 3x1 vector as the output.

The output of each element will be defined by a dot product of a row of your matrix and your vector. So, the first element of out_2 is the dot product of the 1st row of the matrix with your vector, the second element will be the dot product of the 2nd row and your vector and so on. This is just the definition of matrix multiplication, you can read more about it on Wikipedia here

1 Like