Everything about Matrix with Python

Dhiraj Patil
6 min readJul 31, 2022
Image source:- internet

Hello Folks,

In this article we are going to learn Matrix operations with Python.

Matrix is a fundamental topic in learning of Machine Learning and Deep Learning.

Prerequisites:-

  1. Introductory concepts of Matrix.
  2. Hands on experience of Numpy library.

Table of contents:-

  1. Matrix Creation
  2. Datatype of Matrix
  3. Special Matrices
  4. Reading elements of Matrix
  5. Rank, Trace, Inverse of Matrix
  6. Transpose of Matrix
  7. Changing elements of Matrix
  8. Changing positions of columns and rows of Matrix
  9. Reshaping matrix
  10. Arithmetic operations in Matrices
  11. Element-wise Addition, Subtraction, Multiplication, Division of Matrices
  12. Column-Wise, Row-Wise Addition
  13. Dot product of Matrices
  14. Missing Values in Matrix
  15. Index of Missing Values
  16. Stacking of Matrices
  17. Solving Equations:- AX=B

Matrix Creation:-

import numpy as np
A=np.array([[1,2,3],[4,5,6],[7,8,9]])
print('\nMatrix is:-\n',A)
print('\nSize of Matrix is:-\n',A.shape)
output:-
Matrix is:-
[[1 2 3]
[4 5 6]
[7 8 9]]

Size of Matrix is:-
(3, 3)

Datatype of Matrix:-

A=np.array([[1,2],[3,4]])
print('Datatype of matrix A is:-',A.dtype)
B=np.array([[1.5,2],[3,4]])
print('Datatype of matrix B is:-',B.dtype)
print('\nSize of Matrix is:-\n',B.shape)
output:-
Datatype of matrix A is:- int32
Datatype of matrix B is:- float64

Size of Matrix is:-
(2, 2)

Special Matrices:-

print('Zero Matrix of order (2,2):-\n',np.zeros((2,2)))
print('2x2 matrix filled with ones:-\n',np.ones((2,2)))
print('Identity Matrix of order (2,2):-\n',np.eye(2,2))
print('2x2 matrix of random integer numbers between 0 to 100\n',np.random.randint(0,100,(2,2)))
print('Diagonal Matrix of elements (1,2,3)\n',np.diag([1,2,3]))
output:-Zero Matrix of order (2,2):-
[[0. 0.]
[0. 0.]]
2x2 matrix filled with ones:-
[[1. 1.]
[1. 1.]]
Identity Matrix of order (2,2):-
[[1. 0.]
[0. 1.]]
2x2 matrix of random integer numbers between 0 to 100
[[17 83]
[57 86]]
Diagonal Matrix of elements (1,2,3)
[[1 0 0]
[0 2 0]
[0 0 3]]

Reading elements of Matrix:-

A=np.array([[1,2,3],[4,5,6],[7,8,9]])
print('Matrix is:-\n',A)
print('First element of Matrix is:-',A[0,0])
print('First row is:-',A[0,])
print('First column is:-',A[:,0])
print('Element at place 2nd row and 3rd column:-',A[1,2])
output:-
Matrix is:-
[[1 2 3]
[4 5 6]
[7 8 9]]
First element of Matrix is:- 1
First row is:- [1 2 3]
First column is:- [1 4 7]
Element at place 2nd row and 3rd column:- 6

Rank, Trace, Inverse of Matrix:-

M=np.array([[1,2,3],[4,5,6],[7,8,9]])
print('Matrix M\n',M)
print('Rank of M',np.linalg.matrix_rank(M))
print('Rank of M',np.trace(M))
print('\nInverse of M\n',np.linalg.inv(M))
print('det(M)\n',np.linalg.det(M))
output:-
Matrix M
[[1 2 3]
[4 5 6]
[7 8 9]]
Rank of M 2
Rank of M 15

Inverse of M
[[ 3.15251974e+15 -6.30503948e+15 3.15251974e+15]
[-6.30503948e+15 1.26100790e+16 -6.30503948e+15]
[ 3.15251974e+15 -6.30503948e+15 3.15251974e+15]]
det(M)
-9.51619735392994e-16

Transpose of Matrix:-

#Transpose of a Matrix:-
D=np.array([[1,2],[3,4]])
#Method 1
D_trans1=D.T
print('D_trans1:-\n',D_trans1)
#Method 2
D_trans2=np.transpose(D)
print('\nD_trans2:-\n',D_trans2)
output:-D_trans1
[[1 3]
[2 4]]

D_trans2
[[1 3]
[2 4]]

Changing elements of Matrix:-

A=np.array([[1,2,3],[4,5,6],[7,8,9]])
print('Matrix is:-\n',A)
#Replacing element at (0,1) by 100
A[0,1]=100
print(A)
output:-Matrix is:-
[[1 2 3]
[4 5 6]
[7 8 9]]
[[ 1 100 3]
[ 4 5 6]
[ 7 8 9]]
[[ 4 5 6]
[ 1 100 3]
[ 7 8 9]]

Changing positions of columns and rows of Matrix:-

A=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(A)
# Changing first and second row
A[[0,1],:]=A[[1,0],:]
print(A)
output:-[[1 2 3]
[4 5 6]
[7 8 9]]
[[4 5 6]
[1 2 3]
[7 8 9]]
----------------------------------------------------------------
B=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(A)
# Changing first and second columns
B[:,[0,1]]=B[:,[1,0]]
print(B)
output:-
[[1 2 3]
[4 5 6]
[7 8 9]]
[[2 1 3]
[5 4 6]
[8 7 9]]
-----------------------------------------------------------------
C=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(C)
#Reverse rows
C[::-1,:]
#Reverse columns
C=np.array([[1,2],[3,4]])
C[:,::-1]
output:-
[[1 2 3]
[4 5 6]
[7 8 9]]
array([[2, 1],
[4, 3]])
-----------------------------------------------------------------
#Reverse rows as well as columns
D=np.array([[3,4,5],[6,7,8],[0,1,2]])
print(D)
#Method 1
E=D[::-1,::-1]
print('Reverse rows and columns,method 1:-\n',E)
#Method 2
F=np.flip(D)
print('Reverse rows and columns,method 2:-\n',F)
output:-
[[3 4 5]
[6 7 8]
[0 1 2]]
Reverse rows and columns,method 1:-
[[2 1 0]
[8 7 6]
[5 4 3]]
Reverse rows and columns,method 2:-
[[2 1 0]
[8 7 6]
[5 4 3]]

Reshaping matrix:-

A=np.random.randint(0,100,(10,10))
A.shape
B=A.reshape(5,-1)
print('Shape of B',B.shape)
C=A.reshape(-1,2)
print('Shape of C',C.shape)
#Note:-For reshaping of Matrix if you don't sure about number of rows or number of columns then you can put there -1
output:-Shape of B (5, 20)
Shape of C (50, 2)

Arithmetic operations in Matrices:-

A=np.array([[1,2,3],[4,5,6],[7,8,9]])
print('Method1:- Minimum number in Matrix is',A.min())
print('Method2:-Minimum number in Matrix is',np.min(A))
print('Method1:-Maximum number in Matrix is',A.max())
print('Method2:-Minimum number in Matrix is',np.max(A))
print('Method1:-Mean of numbers in Matrix is',A.mean())
print('Method2:-Mean of numbers in Matrix is',np.mean(A))
print('Median of numbers in Matrix is',np.median(A))
print('Variance of numbers in Matrix is',np.var(A))
print('Standard deviation of numbers in Matrix is',np.std(A))
print('INDEX of Minimum number in an array',A.argmin())
print('INDEX of Maximum number in an array',A.argmax())
print('Calculating percentile of numbers in Matrix is',np.percentile(A,75))
output:-Method1:- Minimum number in Matrix is 1
Method2:-Minimum number in Matrix is 1
Method1:-Maximum number in Matrix is 9
Method2:-Minimum number in Matrix is 9
Method1:-Mean of numbers in Matrix is 5.0
Method2:-Mean of numbers in Matrix is 5.0
Median of numbers in Matrix is 5.0
Variance of numbers in Matrix is 6.666666666666667
Standard deviation of numbers in Matrix is 2.581988897471611
INDEX of Minimum number in an array 0
INDEX of Maximum number in an array 8
Calculating percentile of numbers in Matrix is 7.0
-------------------------------------------------------------------# Enumerate for Numpy 2D Arrays or Matrices
for index,value in np.ndenumerate(A):
print(index,value)
output:-
(0, 0) 1
(0, 1) 2
(0, 2) 3
(1, 0) 4
(1, 1) 5
(1, 2) 6
(2, 0) 7
(2, 1) 8
(2, 2) 9

Element-wise Addition, Subtraction, Multiplication, Division of Matrices:-

M=np.array([[1,2],[3,4]])
N=np.array([[5,6],[7,8]])
print('First Matrix \n',M)
print('Second Matrix \n',N)
print('\nMatrix addition (M+N)=> \n',M+N)
print('\nMatrix addition np.add \n',np.add(M,N))
print('\nMatrix subtraction (M-N)=> \n',M-N)
print('\nMatrix subtraction np.subtract \n',np.subtract(M,N))
print('\nMatrix multiplication M*N \n',M*N)
print('\nMatrix multiplication np.multiply \n',np.multiply(M,N))
print('\nMatrix division M/N \n',M/N)
print('\nMatrix division np.divide \n',np.divide(M,N))
output:-
First Matrix
[[1 2]
[3 4]]
Second Matrix
[[5 6]
[7 8]]

Matrix addition (M+N)=>
[[ 6 8]
[10 12]]

Matrix addition np.add
[[ 6 8]
[10 12]]

Matrix subtraction (M-N)=>
[[-4 -4]
[-4 -4]]

Matrix subtraction np.subtract
[[-4 -4]
[-4 -4]]

Matrix multiplication M*N
[[ 5 12]
[21 32]]

Matrix multiplication np.multiply
[[ 5 12]
[21 32]]

Matrix division M/N
[[0.2 0.33333333]
[0.42857143 0.5 ]]

Matrix division np.divide
[[0.2 0.33333333]
[0.42857143 0.5 ]]

Column-Wise, Row-Wise Addition:-

D=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(D)
print('Row-wise summation==>\n',np.sum(D,axis=1))
print('Column-wise summation==>\n',np.sum(D,axis=0))
output:-
[[1 2 3]
[4 5 6]
[7 8 9]]
Row-wise summation==>
[ 6 15 24]
Column-wise summation==>
[12 15 18]

Dot product of Matrices:-

A=np.array([[1,2],[3,4]])
B=np.array([[5,6],[7,8]])
print('Matrix A:-\n',A)
print('Matrix B:-\n',B)
#Method 1
print('Dot product, Method 1:-\n',np.dot(A,B))
#Method 2
print('Dot product, Method 2:-\n',A@B)
#Method 3
print('Dot product, Method 3:-\n',np.matmul(A,B))
output:-Matrix A:-
[[1 2]
[3 4]]
Matrix B:-
[[5 6]
[7 8]]
Dot product, Method 1:-
[[19 22]
[43 50]]
Dot product, Method 2:-
[[19 22]
[43 50]]
Dot product, Method 3:-
[[19 22]
[43 50]]

Missing Values in Matrix:-

# Search for Missing Values and return as a boolean array
B=np.array([[1,np.nan,3],[4,5,6],[7,8,9]])
print('Matrix is:-\n',B)
np.isnan(B)
output:-
Matrix is:-
[[ 1,nan,3]
[ 4,5,6]
[ 7,8,9]]
array([[False, True, False],
[False, False, False],
[False, False, False]])

Index of Missing Values:-

# Index of Missing Values
B=np.array([[1,np.nan,3],[4,5,6],[7,8,9]])
print('Matrix is:-\n',B)
np.where(np.isnan(B))
output:-
Matrix is:-
[[ 1. nan. 3]
[ 4. 5. 6]
[ 7. 8. 9]]
(array([0], dtype=int64), array([1], dtype=int64))

Stacking of Matrices:-

A=np.array([[1,2],[3,4]])
B=np.array([[5,6],[7,8]])
print('First Matrix:-\n',A)
print('Second Matrix:-\n',B)
print('Vertically Stack\n',np.vstack((A,B)))
print('Horizontally Stack\n',np.hstack((A,B)))
output:-
First Matrix:-
[[1 2]
[3 4]]
Second Matrix:-
[[5 6]
[7 8]]
Vertically Stack
[[1 2]
[3 4]
[5 6]
[7 8]]
Horizontally Stack
[[1 2 5 6]
[3 4 7 8]]

Solving Equations:- AX=B

np.random.seed(123)
A = np.array([[1,2,3],[4,5,6],[7,8,9]])
B = np.random.random((3,1))
# 1 st method
X=np.dot(np.linalg.inv(A),B)
print('X\n',X)
# 2nd Method
Y=np.matmul(np.linalg.inv(A),B)
print('Y\n',Y)
# 3rd method
Z=np.linalg.inv(A)@B
print('Z\n',Z)
output:-
X
[[ 1.10666674e+15]
[-2.21333347e+15]
[ 1.10666674e+15]]
Y
[[ 1.10666674e+15]
[-2.21333347e+15]
[ 1.10666674e+15]]
Z
[[ 1.10666674e+15]
[-2.21333347e+15]
[ 1.10666674e+15]]

If you really like this article, please clap and make a comment. I heartly welcome for any suggestion and improvisation.

Thank you!

Connect to me on LinkedIn if you have any queries or want some more insights.

--

--

Dhiraj Patil

Strong background in Mathematics and Statistics with Data Science Program certified, passionate about analytics and learning