Python Matrix Tutorial

Python Matrix

We can implement a Python Matrix in the form of a 2-d List or a 2-d Array. To perform operations on Python Matrix, we need to import Python NumPy Module.

Python Matrix is essential in the field of statistics, data processing, image processing, etc.


Creation of a Python Matrix

Python Matrix can be created using one of the following techniques:

  • By using Lists
  • By using arange() method
  • By using matrix() method

1. Creation of matrix using Lists

The numpy.array() function can be used to create an array using lists as input to it.

Example:

import numpy
input_arr = numpy.array([[ 10, 20, 30],[ 40, 50, 60]])
print(input_arr)

Output:

[[10 20 30]
 [40 50 60]]

As seen above, the output represents a 2-D matrix with the given set of inputs in the form of list.

2. Creation of matrix using ‘numpy.arange()’ function

The numpy.arange() function along with the list inputs can be used to create a matrix in Python.

Example:

import numpy

print(numpy.array([numpy.arange(10,15), numpy.arange(15,20)]))
 

Output:

[[10 11 12 13 14]
 [15 16 17 18 19]]

3. Creation of Matrix using ‘numpy.matrix() function’

The numpy.matrix() function enables us to create a matrix in Python.

Syntax:

numpy.matrix(input,dtype)
  • input: The elements input to form a matrix.
  • dtype: The data type of the corresponding output.

Example:

import numpy as p


matA = p.matrix([[10, 20], [30, 40]])  
print('MatrixA:\n', matA)



matB = p.matrix('[10,20;30,40]', dtype=p.int32)  # Setting the data-type to int
print('\nMatrixB:\n', matB)

Output:

MatrixA:
 [[10 20]
 [30 40]]

MatrixB:
 [[10 20]
 [30 40]]

Addition of Matrix in Python

The addition operation on Matrices can be performed in the following ways:

  • Traditional method
  • By using ‘+’ operator

1. Traditional method

In this traditional method, we basically take the input from the user and then perform the addition operation using the for loops (to traverse through the elements of the matrix) and ‘+’ operator.

Example:

import numpy as p


ar1 = p.matrix([[11, 22], [33, 44]])  
ar2 = p.matrix([[55, 66], [77, 88]])  
res = p.matrix(p.zeros((2,2)))  
print('Matrix ar1 :\n', ar1)
print('\nMatrix ar2 :\n', ar2)

# traditional code
for x in range(ar1.shape[1]):
    for y in range(ar2.shape[0]):
        res[x, y] = ar1[x, y] + ar2[x, y]

print('\nResult :\n', res)


Note:Matrix.shape returns the dimensions of a particular matrix.

Output:

Matrix ar1 :
 [[11 22]
 [33 44]]

Matrix ar2 :
 [[55 66]
 [77 88]]

Result :
 [[  66.   88.]
 [ 110.  132.]]

2. Using ‘+’ operator

This method provides better efficiency to the code as it reduces the LOC (lines of code) and thus, optimizes the code.

Example:

import numpy as p


ar1 = p.matrix([[11, 22], [33, 44]])  
ar2 = p.matrix([[55, 66], [77, 88]])  
res = p.matrix(p.zeros((2,2)))  
print('Matrix ar1 :\n', ar1)
print('\nMatrix ar2 :\n', ar2)

res = ar1 + ar2 # using '+' operator

print('\nResult :\n', res)


Output:

Matrix ar1 :
 [[11 22]
 [33 44]]

Matrix ar2 :
 [[55 66]
 [77 88]]

Result :
 [[ 66  88]
 [110 132]]

Matrix Multiplication in Python

Matrix Multiplication in Python can be provided using the following ways:

  • Scalar Product
  • Matrix Product

Scalar Product

In the scalar product, a scalar/constant value is multiplied by each element of the matrix.

The ‘*’ operator is used to multiply the scalar value with the input matrix elements.

Example:

import numpy as p

matA = p.matrix([[11, 22], [33, 44]])  

print("Matrix A:\n", matA)
print("Scalar Product of Matrix A:\n", matA * 10)


Output:

Matrix A:
 [[11 22]
 [33 44]]
Scalar Product of Matrix A:
 [[110 220]
 [330 440]]

Matrix Product

As mentioned above, we can use the ‘*’ operator only for Scalar multiplication. In order to go ahead with Matrix multiplication, we need to make use of the numpy.dot() function.

The numpy.dot() function takes NumPy arrays as parameter values and performs multiplication according to the basic rules of Matrix Multiplication.

Example:

import numpy as p

matA = p.matrix([[11, 22], [33, 44]])  
matB = p.matrix([[2,2], [2,2]])

print("Matrix A:\n", matA)
print("Matrix B:\n", matB)
print("Dot Product of Matrix A and Matrix B:\n", p.dot(matA, matB))

Output:

Matrix A:
 [[11 22]
 [33 44]]
Matrix B:
 [[2 2]
 [2 2]]
Dot Product of Matrix A and Matrix B:
 [[ 66  66]
 [154 154]]

Subtraction of Python Matrix

The ‘-‘ operator is used to perform Subtraction on Python Matrix.

Example:

import numpy as p

matA = p.matrix([[11, 22], [33, 44]])  
matB = p.matrix([[2,2], [2,2]])

print("Matrix A:\n", matA)
print("Matrix B:\n", matB)
print("Subtraction of Matrix A and Matrix B:\n",(matA - matB))
 

Output:

Matrix A:
 [[11 22]
 [33 44]]
Matrix B:
 [[2 2]
 [2 2]]
Subtraction of Matrix A and Matrix B:
 [[ 9 20]
 [31 42]]

Division of Python Matrix

Scalar Division can be performed on the elements of the Matrix in Python using the ‘/’ operator.

The ‘/’ operator divides each element of the Matrix with a scalar/constant value.

Example:

import numpy as p


matB = p.matrix([[2,2], [2,2]])


print("Matrix B:\n", matB)
print("Matrix B after Scalar Division operation:\n",(matB/2))
 

Output:

Matrix B:
 [[2 2]
 [2 2]]
Matrix B after Scalar Division operation:
 [[ 1.  1.]
 [ 1.  1.]]

Transpose of a Python Matrix

Transpose of a matrix basically involves the flipping of matrix over the corresponding diagonals i.e. it exchanges the rows and the columns of the input matrix. The rows become the columns and vice-versa.

For example: Let’s consider a matrix A with dimensions 3×2 i.e 3 rows and 2 columns. After performing transpose operation, the dimensions of the matrix A would be 2×3 i.e 2 rows and 3 columns.

Matrix.T basically performs the transpose of the input matrix and produces a new matrix as a result of the transpose operation.

Example:

import numpy
 
matA = numpy.array([numpy.arange(10,15), numpy.arange(15,20)])
print("Original Matrix A:\n")
print(matA)
print('\nDimensions of the original MatrixA: ',matA.shape)
print("\nTranspose of Matrix A:\n ")
res = matA.T
print(res)
print('\nDimensions of the Matrix A after performing the Transpose Operation:  ',res.shape)

Output:

Original Matrix A:

[[10 11 12 13 14]
 [15 16 17 18 19]]

Dimensions of the original MatrixA: (2, 5)

Transpose of Matrix A:
 
[[10 15]
 [11 16]
 [12 17]
 [13 18]
 [14 19]]

Dimensions of the Matrix A after performing the Transpose Operation: (5, 2)

In the above snippet of code, I have created a matrix of dimensions 2×5 i.e. 2 rows and 5 columns.

After performing the transpose operation, the dimensions of the resultant matrix are 5×2 i.e. 5 rows and 2 columns.


Exponent of a Python Matrix

The exponent on a Matrix is calculated element-wise i.e. exponent of every element is calculated by raising the element to the power of an input scalar/constant value.

Example:

import numpy
 
matA = numpy.array([numpy.arange(0,2), numpy.arange(2,4)])
print("Original Matrix A:\n")
print(matA)
print("Exponent of the input matrix:\n")
print(matA ** 2) # finding the exponent of every element of the matrix

Output:

Original Matrix A:

[[0 1]
 [2 3]]

Exponent of the input matrix:

[[0 1]
 [4 9]]

In the above code snippet, we have found out the exponent of every element of the input matrix by raising it to the power of 2.


Matrix Multiplication Operation using NumPy Methods

The following techniques can be used to perform NumPy Matrix multiplication:

  • Using the multiply() method
  • Using the matmul() method
  • Using the dot() method – Already covered in this article

Method 1: Using the multiply() method

The numpy.multiply() method performs element-wise multiplication on an input matrix.

Example:

import numpy as p


matA = p.matrix([[10, 20], [30, 40]])  
print('MatrixA:\n', matA)



matB = p.matrix('[10,20;30,40]', dtype=p.int32)  # Setting the data-type to int
print('\nMatrixB:\n', matB)

print("Matrix multplication using numpy.matrix() method")
res = p.multiply(matA,matB)
print(res)

Output:

MatrixA:
 [[10 20]
 [30 40]]

MatrixB:
 [[10 20]
 [30 40]]
Matrix multplication using numpy.matrix() method
[[ 100  400]
 [ 900 1600]]

Method 2: Using the matmul() method

The numpy.matmul() method performs the matrix product on the input matrices.

Example:

import numpy as p


matA = p.matrix([[10, 20], [30, 40]])  
print('MatrixA:\n', matA)



matB = p.matrix('[10,20;30,40]', dtype=p.int32)  # Setting the data-type to int
print('\nMatrixB:\n', matB)

print("Matrix multplication using numpy.matmul() method")
res = p.matmul(matA,matB)
print(res)

Output:

MatrixA:
 [[10 20]
 [30 40]]

MatrixB:
 [[10 20]
 [30 40]]
Matrix multplication using numpy.matmul() method
[[ 700 1000]
 [1500 2200]]

I would strongly recommend all the readers to go through the below tutorial to have a thorough understanding of NumPy Matrix Multiplication: NumPy Matrix Multiplication


NumPy Matrix Transpose

The numpy.transpose() function performs the transpose on the input matrix and results in a new matrix.

Example:

import numpy
 
matA = numpy.array([numpy.arange(10,15), numpy.arange(15,20)])
print("Original Matrix A:\n")
print(matA)
print('\nDimensions of the original MatrixA: ',matA.shape)
print("\nTranspose of Matrix A:\n ")
res = matA.transpose()
print(res)
print('\nDimensions of the Matrix A after performing the Transpose Operation:  ',res.shape)

Output:

Original Matrix A:

[[10 11 12 13 14]
 [15 16 17 18 19]]

Dimensions of the original MatrixA: (2, 5)

Transpose of Matrix A:
 
[[10 15]
 [11 16]
 [12 17]
 [13 18]
 [14 19]]

Dimensions of the Matrix A after performing the Transpose Operation: (5, 2)

Recommended read: NumPy Matrix transpose() function


Conclusion

Thus, in this article, we have understood the operations performed on Python Matrix and also had a look at the NumPy Matrix operations.


References