Python Matrix
What does Python Matrix mean?
In general, a matrix is a mathematical concept to represent equations in a 2-D structure, using rows and columns.
Python Matrix:
In python, we do not have an inbuilt matrix, but we can make it using arrays or lists. If we want to define a matrix in python, we can say that a Matrix is a list of lists or it is an Array of arrays.
Example:
# list approach to make a Matrixmatrix = [[1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14,15]
]
Few examples Matrix:
matrix = [ [1,2,3,4],
[100,200,300,400],
[1000,2000,3000,4000]
]
print("The First Row of the matrix", matrix[0])
print("The Second Row of the matrix", matrix[1])
print("The Third Row of the matrix", matrix[2])
NumPy Arrays:
NumPy is an outsider library for python, which is generally utilized for information science. NumPy contains numerous numerical techniques and it likewise upholds arrays. The NumPy arrays are more effective than standard python cluster modules since we can perform matrix activities like matrix addition, matrix multiplication, matrix subtraction, etc using NumPy arrays.
Example:
from numpy import array
arr = array([2,4,8,12,26])
print(arr)
print(type(arr)
Output:
[ 2 4 8 12 26]
<class 'numpy.ndarray'>
Matrix Operations:
- Matrix Addition:
Example:
import numpy as np
A = np.array([ [1,2,3], [4,5,6], [7,8,9]])
B = np.array([[7,8,9],[4,5,6],[1,2,3]])
print("Matrix Addtion")
print(A+B)
Output:
Matrix Addtion
[[ 8 10 12]
[ 8 10 12]
[ 8 10 12]]
Matrix Subtraction:
Example:
import numpy as np
A = np.array([ [1,2,3], [4,5,6], [7,8,9]])
B = np.array([[7,8,9],[4,5,6],[1,2,3]])
print("Matrix Subtraction")
print(A-B)
Output:
Matrix Subtraction[[-6 -6 -6]
[ 0 0 0]
[ 6 6 6]]
Matrix Multiplication:
Example:
import numpy as np
A = np.array([ [1,2,3], [4,5,6], [7,8,9]])
B = np.array([[7,8,9],[4,5,6],[1,2,3]])
print("Matrix Multipication")
print(A.dot(B))
Output:
Matrix Multipication[[ 18 24 30]
[ 54 69 84]
[ 90 114 138]]
Transpose a matrix:
Example:
import numpy as np
A = np.array([ [1,2,3], [4,5,6], [7,8,9]])
print("A Transpose")
print(A.transpose())
Output:
A Transpose
[[1 4 7]
[2 5 8]
[3 6 9]]
Matrix Slicing:
To slice a matrix we use a special syntax matrix[row, columns].
Example:
import numpy as np
arr = np.array([1,2,3,4,5,6,7])
matrix = np.array([ [1,2,3], [4,5,6], [7,8,9]])
print(matrix[:2, :4]) # two rows, four columns
print("***************")
print(matrix[:1,]) # first row, all columns
print("***************")
print(matrix[:,2]) # all rows, second column
print("***************")
print(matrix[:, 2:5]) # all rows, third to fifth column
Output:
[[1 2 3]
[4 5 6]]
***************
[[1 2 3]]
***************
[3 6 9]
***************
[[3]
[6]
[9]]