Numpy Tutorial
Creating NumPy Array
NumPy Array Manipulation
Matrix in NumPy
Operations on NumPy Array
Reshaping NumPy Array
Indexing NumPy Array
Arithmetic operations on NumPy Array
Linear Algebra in NumPy Array
NumPy and Random Data
Sorting and Searching in NumPy Array
Universal Functions
Working With Images
Projects and Applications with NumPy
Matrix manipulation is a foundational concept in numerical computing, and NumPy is well-equipped to handle various matrix manipulations. In this tutorial, we'll explore common operations to manipulate matrices using NumPy.
Ensure you have NumPy installed:
pip install numpy
Then, import the necessary library:
import numpy as np
# Create a 2x3 matrix filled with zeros matrix_zeros = np.zeros((2, 3)) print(matrix_zeros) # Outputs: # [[0. 0. 0.] # [0. 0. 0.]] # Create a 3x3 matrix filled with ones matrix_ones = np.ones((3, 3)) print(matrix_ones) # Outputs: # [[1. 1. 1.] # [1. 1. 1.] # [1. 1. 1.]]
To transpose a matrix, you interchange rows and columns.
matrix = np.array([[1, 2, 3], [4, 5, 6]]) transposed = matrix.T print(transposed) # Outputs: # [[1 4] # [2 5] # [3 6]]
To multiply matrices, use np.dot()
. Remember, the number of columns in the first matrix should equal the number of rows in the second matrix.
A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) result = np.dot(A, B) print(result) # Outputs: # [[19 22] # [43 50]]
To get the inverse of a matrix, use np.linalg.inv()
. Note: not all matrices are invertible.
matrix = np.array([[4, 7], [2, 6]]) inverse_matrix = np.linalg.inv(matrix) print(inverse_matrix)
To compute the determinant of a matrix, use np.linalg.det()
.
matrix = np.array([[4, 7], [2, 6]]) determinant = np.linalg.det(matrix) print(determinant)
To find the rank of a matrix, use np.linalg.matrix_rank()
.
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) rank = np.linalg.matrix_rank(matrix) print(rank)
A = np.array([[1, 2], [3, 4]]) B = np.array([[2, 2], [2, 2]]) # Element-wise addition print(A + B) # Outputs: # [[3 4] # [5 6]] # Element-wise multiplication (not a dot product) print(A * B) # Outputs: # [[2 4] # [6 8]]
To change the shape of a matrix, use the reshape
method:
matrix = np.array([[1, 2, 3], [4, 5, 6]]) # Reshape to 3x2 matrix reshaped = matrix.reshape(3, 2) print(reshaped) # Outputs: # [[1 2] # [3 4] # [5 6]]
To convert a matrix into a 1D array, use the flatten
method:
matrix = np.array([[1, 2, 3], [4, 5, 6]]) flattened = matrix.flatten() print(flattened) # Outputs: [1 2 3 4 5 6]
NumPy provides a comprehensive set of functions for matrix manipulations, making it indispensable for scientific computing in Python. Mastery of matrix operations is crucial for tasks in linear algebra, machine learning, data analysis, and other domains.
Description: NumPy provides a wide range of matrix operations, including addition, subtraction, multiplication, and more.
Code:
import numpy as np # Create two matrices matrix1 = np.array([[1, 2], [3, 4]]) matrix2 = np.array([[5, 6], [7, 8]]) # Matrix addition result_addition = np.add(matrix1, matrix2) # Matrix subtraction result_subtraction = np.subtract(matrix1, matrix2) # Element-wise matrix multiplication result_elementwise_mult = np.multiply(matrix1, matrix2) # Element-wise matrix division result_elementwise_div = np.divide(matrix1, matrix2) print("Matrix 1:") print(matrix1) print("Matrix 2:") print(matrix2) print("Matrix Addition:") print(result_addition) print("Matrix Subtraction:") print(result_subtraction) print("Element-wise Multiplication:") print(result_elementwise_mult) print("Element-wise Division:") print(result_elementwise_div)
Description: NumPy's linear algebra module (numpy.linalg
) provides functions for various linear algebra operations.
Code:
import numpy as np # Create a square matrix matrix = np.array([[1, 2], [3, 4]]) # Matrix determinant det = np.linalg.det(matrix) # Matrix trace trace = np.trace(matrix) # Matrix inverse inverse_matrix = np.linalg.inv(matrix) print("Original Matrix:") print(matrix) print("Determinant:", det) print("Trace:", trace) print("Inverse Matrix:") print(inverse_matrix)
Description: Performing element-wise matrix operations like exponentiation, square root, and logarithm.
Code:
import numpy as np # Create a matrix matrix = np.array([[1, 2], [3, 4]]) # Element-wise matrix exponentiation result_exponentiation = np.exp(matrix) # Element-wise square root result_sqrt = np.sqrt(matrix) # Element-wise logarithm result_log = np.log(matrix) print("Original Matrix:") print(matrix) print("Element-wise Exponentiation:") print(result_exponentiation) print("Element-wise Square Root:") print(result_sqrt) print("Element-wise Logarithm:") print(result_log)
Description: Manipulating matrices includes reshaping, transposing, and flattening.
Code:
import numpy as np # Create a matrix matrix = np.array([[1, 2], [3, 4]]) # Reshape the matrix reshaped_matrix = np.reshape(matrix, (1, 4)) # Transpose the matrix transposed_matrix = np.transpose(matrix) # Flatten the matrix flattened_matrix = matrix.flatten() print("Original Matrix:") print(matrix) print("Reshaped Matrix:") print(reshaped_matrix) print("Transposed Matrix:") print(transposed_matrix) print("Flattened Matrix:") print(flattened_matrix)
Description: Performing matrix multiplication using np.dot
or the @
operator.
Code:
import numpy as np # Create two matrices matrix1 = np.array([[1, 2], [3, 4]]) matrix2 = np.array([[5, 6], [7, 8]]) # Matrix multiplication using np.dot result_dot = np.dot(matrix1, matrix2) # Matrix multiplication using @ operator result_operator = matrix1 @ matrix2 print("Matrix 1:") print(matrix1) print("Matrix 2:") print(matrix2) print("Matrix Multiplication using np.dot:") print(result_dot) print("Matrix Multiplication using @ operator:") print(result_operator)
Description: Finding the inverse of a matrix using np.linalg.inv
.
Code:
import numpy as np # Create a square matrix matrix = np.array([[1, 2], [3, 4]]) # Matrix inversion inverse_matrix = np.linalg.inv(matrix) print("Original Matrix:") print(matrix) print("Inverse Matrix:") print(inverse_matrix)
Description: Computing eigenvalues and eigenvectors of a matrix using np.linalg.eig
.
Code:
import numpy as np # Create a square matrix matrix = np.array([[1, 2], [3, 4]]) # Eigenvalue and eigenvector computation eigenvalues, eigenvectors = np.linalg.eig(matrix) print("Original Matrix:") print(matrix) print("Eigenvalues:") print(eigenvalues) print("Eigenvectors:") print(eigenvectors)
Description: Solving linear equations using np.linalg.solve
.
Code:
import numpy as np # Coefficient matrix coeff_matrix = np.array([[2, 3], [4, 5]]) # Right-hand side vector rhs_vector = np.array([5, 6]) # Solve linear equations solution = np.linalg.solve(coeff_matrix, rhs_vector) print("Coefficient Matrix:") print(coeff_matrix) print("Right-hand Side Vector:") print(rhs_vector) print("Solution to Linear Equations:") print(solution)
Description: Performing matrix decomposition, such as LU decomposition or singular value decomposition (SVD).
Code:
import numpy as np # Create a square matrix matrix = np.array([[1, 2], [3, 4]]) # LU decomposition lu_matrix, pivots = np.linalg.lu(matrix) # Singular value decomposition (SVD) u, s, vh = np.linalg.svd(matrix) print("Original Matrix:") print(matrix) print("LU Decomposition:") print("LU Matrix:") print(lu_matrix) print("Pivots:") print(pivots) print("Singular Value Decomposition:") print("U Matrix:") print(u) print("Singular Values:") print(s) print("Vh Matrix:") print(vh)