Matrices
Matrices
Matrices in Python
Matrices in Python
• Python does not have a straightforward way to implement a matrix
data type.
• The python matrix makes use of arrays, and the same can be
implemented.
• List = [[Row1],
[Row2],
[Row3]
...
[RowN]]
Create Python Matrix using a nested list data
type
Create Python Matrix using a nested list data
type
• M1 = [[8, 14, -6],
[12,7,4],
[-11,3,21]]
matrix_length = len(M1)
matrix_length = len(M1)
• pass a list, tuple or any array-like object into the array() method, and it will be
converted into an ndarray (short name for N-dimensional array)
import numpy as np
[[ 12 -12 36]
[ 16 12 48]
[ 6 -12 60]]
Matrix Subtraction
To perform subtraction on the matrix, we will create two matrices using
numpy.array() and subtract them using the (-) operator.
import numpy as np
M1 = np.array([[3, 6, 9], [5, -10, 15], [-7, 14, 21]])
M2 = np.array([[9, -18, 27], [11, 22, 33], [13, -26, 39]])
M3 = M1 - M2
print(M3)
[[ -6 24 -18]
[ -6 -32 -18]
[-20 40 -18]]
Matrix Multiplication
• To multiply them will, you can make use of numpy dot() method.
• Numpy.dot() is the dot product of matrix M1 and M2.
• Numpy.dot() handles the 2D arrays and perform matrix multiplications
• import numpy as np
import numpy as np
M1 = np.array([[3, 6, 9], [5, -10, 15], [4,8,12]])
M2 = M1.transpose()
print(M2)
[[ 3 5 4]
[ 6 -10 8]
[ 9 15 12]]
To print all rows and third columns
import numpy as np
M1 = np.array([[2, 4, 6, 8, 10],
[3, 6, 9, -12, -15],
[4, 8, 12, 16, -20],
[5, -10, 15, -20, 25]])
print(M1[:,3]) # This will print all rows and the third column data.
[ 8 -12 16 -20]
[[ 2 4 6 8 10]]
[[ 2 4 6 8 10]]
To print the first three rows and first 2 columns
import numpy as np
M1 = np.array([[2, 4, 6, 8, 10],
[3, 6, 9, -12, -15],
[4, 8, 12, 16, -20],
[5, -10, 15, -20, 25]])
print(M1[:3,:2])
[[2 4]
[3 6]
[4 8]]
To print the rows of the matrix
import numpy as np
M1 = np.array([[3, 6, 9], [5, -10, 15], [4,8,12]])
print(M1[0]) #first row
print(M1[1]) # the second row
print(M1[-1]) # -1 will print the last row
[3 6 9]
[ 5 -10 15]
[ 4 8 12]