Learn practical skills, build real-world projects, and advance your career

Performing Matrix Operations Using Pytorch Functions

We will perform different types of matrix operations using pytorch functions.

PyTorch is an open source machine learning library. Tensors are classes in Pytorch used to store and perform different types of operations on multidimensional arrays. We have chosen 5 tensor functions and see how these functions ca be used to peform respective matrix operation.

  • torch.matmul()
  • torch.transpose()
  • torch.inverse()
  • torch.trace()
  • torch.eig()
# Import torch and other required modules
import torch

Function 1 - torch.matmul()

Helps to multiply two matrices.
The syntax of the funtion is: torch.matmul(input, other, out=None)

# Example 1 - working 
a=torch.tensor([[1,2,3], [4,5,6],[7,8,9]])
b=torch.tensor([[10,11,12], [13,14,15],[16,17,18]])
c=torch.matmul(a,b)
print ("A=",a)
print("B=",b)
print ("Matrix Multiplication of A & B:",c)
A= tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) B= tensor([[10, 11, 12], [13, 14, 15], [16, 17, 18]]) Matrix Multiplication of A & B: tensor([[ 84, 90, 96], [201, 216, 231], [318, 342, 366]])

We have taken two matices 'a' and 'b', and matrix 'c' computes the product of matrix 'a' & 'b'.