PyTorch torch.matmul() method is “used to calculate the matrix product of two tensors.”
Syntax
torch.matmul(input, other, *, out=None)
Parameters
- input: It is the first input tensor.
- other: It is the second input tensor.
- out: It is the output tensor (optional).
Some Important Notes
- For 2-D tensors: It performs the matrix multiplication just as expected: out = input × other
- For 1-D tensors: It performs the inner (dot) product of vectors: out = input ⋅ other
- For N-D tensors: If either input or other is N-D (N > 2), it is treated as a stack of matrices residing in the last two dimensions, and batch matrix multiplication is performed.
- Broadcasting: If input dimensions and others don’t match exactly, torch.matmul() will try to broadcast them.
Example 1: Simple 2D Matrix Multiplication
import torch
a = torch.tensor([[1, 2],
[3, 4]])
b = torch.tensor([[5, 6],
[7, 8]])
result = torch.matmul(a, b)
print(result)
Output
tensor([[19, 22],
[43, 50]])
Example 2: Dot Product of 1D Tensors
import torch
a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5, 6])
result = torch.matmul(a, b)
print(result)
Output
tensor(32)
Example 3: Batch Matrix Multiplication
import torch
a = torch.randn(3, 2, 4) # Batch of 3 matrices
b = torch.randn(3, 4, 3) # Batch of 3 matrices
result = torch.matmul(a, b)
print(result)
Output
That’s it!
Related posts

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Machine Learning frameworks like PyTorch and Tensorflow is a testament to his versatility and commitment to the craft.