The NumPy matrix library provides functions for creating and manipulating matrices. This library allows you to perform a wide range of matrix operations, including matrix multiplication, inversion, and decomposition.
In NumPy, matrices can be created using the numpy.matrix() function or by converting existing arrays to matrices. This tutorial will cover different methods to create matrices.
The numpy.matrix() function is used to create a matrix from a string representation or from existing data structures. This function is best suitable for creating small matrices quickly.
In the following example, we are creating a matrix from a string representation and from an existing array. The np.matrix() function interprets the string as a 2×2 matrix, and the array is directly converted to a matrix format −
# Open Compiler
import numpy as np
# Creating a matrix from a string
matrix_str = np.matrix('1 2; 3 4')
print("Matrix from string:n", matrix_str)
# Creating a matrix from an array
array_data = np.array([[1, 2], [3, 4]])
matrix_from_array = np.matrix(array_data)
print("Matrix from array:n", matrix_from_array)
Output:
Following is the output obtained −
Matrix from string:
[[1 2]
[3 4]]
Matrix from array:
[[1 2]
[3 4]]
You can convert a NumPy array into a matrix using the numpy.asmatrix() function. This is useful when you have existing data in array form on which you want to perform matrix operations.
In the example below, we are creating an array and then converting it to a matrix using np.asmatrix() function −
# Open Compiler
import numpy as np
# Creating an array
array_data = np.array([[5, 6], [7, 8]])
# Converting array to matrix
matrix_data = np.asmatrix(array_data)
print("Converted Matrix:n", matrix_data)
Output:
This will produce the following result −
Converted Matrix:
[[5 6]
[7 8]]
Once you have created a matrix, you can perform a wide range of matrix operations, such as addition, multiplication, transpose, inversion, and more.
Adding two matrices involves adding the corresponding elements. If two matrices have the same shape, you can add them together element-wise.
In this example, “matrix_1” and “matrix_2” are added together element-wise, meaning each element of “matrix_1” is added to the corresponding element in “matrix_2” −
# Open Compiler import numpy as np # Add two matrices matrix_1 = np.array([[1, 2], [3, 4]]) matrix_2 = np.array([[5, 6], [7, 8]]) result = matrix_1 + matrix_2 print(result)
Output:
Following is the output of the above code −
[[ 6 8]
[10 12]]
We can perform matrix multiplication using the following ways −
* operator@ operator (Python 3.5+)np.dot() functionnumpy.matmul() functionUnlike element-wise multiplication, matrix multiplication follows the linear algebra rules.
In this example, we are multiplying two matrices using all the above given ways −
# Open Compiler
import numpy as np
matrix_1 = np.array([[1, 2], [3, 4]])
matrix_2 = np.array([[5, 6], [7, 8]])
# Matrix multiplication using *
matrix_product1 = matrix_1 * matrix_2
print("Matrix Multiplication (*):n", matrix_product1)
# Matrix multiplication using @
matrix_product2 = matrix_1 @ matrix_2
print("Matrix Multiplication (@):n", matrix_product2)
# Matrix multiplication using np.dot()
matrix_product3 = np.dot(matrix_1, matrix_2)
print("Matrix Multiplication (np.dot()):n", matrix_product3)
# Matrix multiplication using np.matmul()
matrix_product4 = np.matmul(matrix_1, matrix_2)
print("Matrix Multiplication (np.matmul()):n", matrix_product4)
Output:
The output obtained is as shown below −
Matrix Multiplication (*):
[[ 5 12]
[21 32]]
Matrix Multiplication (@):
[[19 22]
[43 50]]
Matrix Multiplication (np.dot()):
[[19 22]
[43 50]]
Matrix Multiplication (np.matmul()):
[[19 22]
[43 50]]
Matrix inversion is an operation to find a matrix that, when multiplied by the original matrix, yields the identity matrix. The inverse of a matrix can be calculated using the np.linalg.inv() function.
However, not all matrices are invertible. A matrix must be square and have a non-zero determinant to be invertible.
In the following example, we are inverting a 2×2 matrix using np.linalg.inv() function. The output is a new matrix that, when multiplied by the original, results in the identity matrix −
# Open Compiler import numpy as np matrix = np.array([[1, 2], [3, 4]]) inverse_matrix = np.linalg.inv(matrix) print(inverse_matrix)
Output:
After executing the above code, we get the following output −
[[-2. 1. ]
[ 1.5 -0.5]]
Transposing a matrix involves flipping it over its diagonal, swapping the row and column indices. We can transpose a matrix in NumPy using the .T attribute.
In the following example, we are transposing a 2×2 matrix using the “.T” attribute −
# Open Compiler import numpy as np # Transpose of a matrix matrix = np.array([[1, 2], [3, 4]]) transposed = matrix.T print(transposed)
Output:
The result produced is as follows −
[[1 3]
[2 4]]
The determinant of a matrix is a scalar value that can be calculated using the np.linalg.det() function. It provides information about the matrix’s properties, such as whether it is invertible.
A non-zero determinant indicates that the matrix is invertible, while a determinant of zero means the matrix is singular.
In this example, np.linalg.det() function computes the determinant of the given matrix −
# Open Compiler
import numpy as np
# Compute the determinant
matrix = np.array([[1, 2], [3, 4]])
det = np.linalg.det(matrix)
print("Determinant:", det)
Output:
We get the output as shown below −
Determinant: -2.0000000000000004
The numpy.linalg.eig() function is used to compute the eigenvalues and right eigenvectors of a square matrix. The eigenvalues indicate the magnitude of the vectors, while the eigenvectors provide the directions.
Eigenvalues and eigenvectors are fundamental concepts in linear algebra, and are important in many areas such as PCA (Principal Component Analysis) and solving differential equations.
In this example, the np.linalg.eig() function computes the eigenvalues and eigenvectors of the matrix. Eigenvalues indicate the magnitude of scaling along each eigenvector direction −
# Open Compiler
import numpy as np
# Compute eigenvalues and eigenvectors
matrix = np.array([[4, -2], [1, 1]])
eigvals, eigvecs = np.linalg.eig(matrix)
print("Eigenvalues:", eigvals)
print("Eigenvectors:", eigvecs)
Output:
Following is the output obtained −
Eigenvalues: [3. 2.]
Eigenvectors:
[[0.89442719 0.70710678]
[0.4472136 0.70710678]]
SVD is a factorization method for matrices that generalizes the eigendecomposition of a square matrix to any m x n matrix. We can achieve this in NumPy using the numpy.linalg.svd() function.
Eigendecomposition is the process of breaking a matrix down into its eigenvalues and eigenvectors. These eigenvalues represent the scaling factor, while the eigenvectors show the directions in which the matrix stretches or compresses.
In the following example, we are performing singular value decomposition on a “2×2” matrix using np.linalg.svd() function. The result includes the U matrix, singular values, and the V matrix, which together represent the original matrix −
# Open Compiler
import numpy as np
matrix_a = np.matrix('1 2; 3 4')
# Performing SVD
U, S, V = np.linalg.svd(matrix_a)
print("U Matrix:n", U)
print("Singular Values:n", S)
print("V Matrix:n", V)
Output:
This will produce the following result −
U Matrix:
[[-0.40455358 -0.9145143 ]
[-0.9145143 0.40455358]]
Singular Values:
[5.4649857 0.36596619]
V Matrix:
[[-0.57604844 -0.81741556]
[ 0.81741556 -0.57604844]]
Key Takeaway: Master the NumPy matrix library with Vista Academy!