
- NumPy - Home
- NumPy - Introduction
- NumPy - Environment
- NumPy Arrays
- NumPy - Ndarray Object
- NumPy - Data Types
- NumPy Creating and Manipulating Arrays
- NumPy - Array Creation Routines
- NumPy - Array Manipulation
- NumPy - Array from Existing Data
- NumPy - Array From Numerical Ranges
- NumPy - Iterating Over Array
- NumPy - Reshaping Arrays
- NumPy - Concatenating Arrays
- NumPy - Stacking Arrays
- NumPy - Splitting Arrays
- NumPy - Flattening Arrays
- NumPy - Transposing Arrays
- NumPy Indexing & Slicing
- NumPy - Indexing & Slicing
- NumPy - Indexing
- NumPy - Slicing
- NumPy - Advanced Indexing
- NumPy - Fancy Indexing
- NumPy - Field Access
- NumPy - Slicing with Boolean Arrays
- NumPy Array Attributes & Operations
- NumPy - Array Attributes
- NumPy - Array Shape
- NumPy - Array Size
- NumPy - Array Strides
- NumPy - Array Itemsize
- NumPy - Broadcasting
- NumPy - Arithmetic Operations
- NumPy - Array Addition
- NumPy - Array Subtraction
- NumPy - Array Multiplication
- NumPy - Array Division
- NumPy Advanced Array Operations
- NumPy - Swapping Axes of Arrays
- NumPy - Byte Swapping
- NumPy - Copies & Views
- NumPy - Element-wise Array Comparisons
- NumPy - Filtering Arrays
- NumPy - Joining Arrays
- NumPy - Sort, Search & Counting Functions
- NumPy - Searching Arrays
- NumPy - Union of Arrays
- NumPy - Finding Unique Rows
- NumPy - Creating Datetime Arrays
- NumPy - Binary Operators
- NumPy - String Functions
- NumPy - Matrix Library
- NumPy - Linear Algebra
- NumPy - Matplotlib
- NumPy - Histogram Using Matplotlib
- NumPy Sorting and Advanced Manipulation
- NumPy - Sorting Arrays
- NumPy - Sorting along an axis
- NumPy - Sorting with Fancy Indexing
- NumPy - Structured Arrays
- NumPy - Creating Structured Arrays
- NumPy - Manipulating Structured Arrays
- NumPy - Record Arrays
- Numpy - Loading Arrays
- Numpy - Saving Arrays
- NumPy - Append Values to an Array
- NumPy - Swap Columns of Array
- NumPy - Insert Axes to an Array
- NumPy Handling Missing Data
- NumPy - Handling Missing Data
- NumPy - Identifying Missing Values
- NumPy - Removing Missing Data
- NumPy - Imputing Missing Data
- NumPy Performance Optimization
- NumPy - Performance Optimization with Arrays
- NumPy - Vectorization with Arrays
- NumPy - Memory Layout of Arrays
- Numpy Linear Algebra
- NumPy - Linear Algebra
- NumPy - Matrix Library
- NumPy - Matrix Addition
- NumPy - Matrix Subtraction
- NumPy - Matrix Multiplication
- NumPy - Element-wise Matrix Operations
- NumPy - Dot Product
- NumPy - Matrix Inversion
- NumPy - Determinant Calculation
- NumPy - Eigenvalues
- NumPy - Eigenvectors
- NumPy - Singular Value Decomposition
- NumPy - Solving Linear Equations
- NumPy - Matrix Norms
- NumPy Element-wise Matrix Operations
- NumPy - Sum
- NumPy - Mean
- NumPy - Median
- NumPy - Min
- NumPy - Max
- NumPy Set Operations
- NumPy - Unique Elements
- NumPy - Intersection
- NumPy - Union
- NumPy - Difference
- NumPy Random Number Generation
- NumPy - Random Generator
- NumPy - Permutations & Shuffling
- NumPy - Uniform distribution
- NumPy - Normal distribution
- NumPy - Binomial distribution
- NumPy - Poisson distribution
- NumPy - Exponential distribution
- NumPy - Rayleigh Distribution
- NumPy - Logistic Distribution
- NumPy - Pareto Distribution
- NumPy - Visualize Distributions With Sea born
- NumPy - Matplotlib
- NumPy - Multinomial Distribution
- NumPy - Chi Square Distribution
- NumPy - Zipf Distribution
- NumPy File Input & Output
- NumPy - I/O with NumPy
- NumPy - Reading Data from Files
- NumPy - Writing Data to Files
- NumPy - File Formats Supported
- NumPy Mathematical Functions
- NumPy - Mathematical Functions
- NumPy - Trigonometric functions
- NumPy - Exponential Functions
- NumPy - Logarithmic Functions
- NumPy - Hyperbolic functions
- NumPy - Rounding functions
- NumPy Fourier Transforms
- NumPy - Discrete Fourier Transform (DFT)
- NumPy - Fast Fourier Transform (FFT)
- NumPy - Inverse Fourier Transform
- NumPy - Fourier Series and Transforms
- NumPy - Signal Processing Applications
- NumPy - Convolution
- NumPy Polynomials
- NumPy - Polynomial Representation
- NumPy - Polynomial Operations
- NumPy - Finding Roots of Polynomials
- NumPy - Evaluating Polynomials
- NumPy Statistics
- NumPy - Statistical Functions
- NumPy - Descriptive Statistics
- NumPy Datetime
- NumPy - Basics of Date and Time
- NumPy - Representing Date & Time
- NumPy - Date & Time Arithmetic
- NumPy - Indexing with Datetime
- NumPy - Time Zone Handling
- NumPy - Time Series Analysis
- NumPy - Working with Time Deltas
- NumPy - Handling Leap Seconds
- NumPy - Vectorized Operations with Datetimes
- NumPy ufunc
- NumPy - ufunc Introduction
- NumPy - Creating Universal Functions (ufunc)
- NumPy - Arithmetic Universal Function (ufunc)
- NumPy - Rounding Decimal ufunc
- NumPy - Logarithmic Universal Function (ufunc)
- NumPy - Summation Universal Function (ufunc)
- NumPy - Product Universal Function (ufunc)
- NumPy - Difference Universal Function (ufunc)
- NumPy - Finding LCM with ufunc
- NumPy - ufunc Finding GCD
- NumPy - ufunc Trigonometric
- NumPy - Hyperbolic ufunc
- NumPy - Set Operations ufunc
- NumPy Useful Resources
- NumPy - Quick Guide
- NumPy - Cheatsheet
- NumPy - Useful Resources
- NumPy - Discussion
- NumPy Compiler
NumPy - Matrix Library
The NumPy Matrix Library
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.
Using numpy.matrix() Function
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.
Example
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 2x2 matrix, and the array is directly converted to a matrix format −
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)
Following is the output obtained −
Matrix from string: [[1 2] [3 4]] Matrix from array: [[1 2] [3 4]]
Using numpy.array() Function
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.
Example
In the example below, we are creating an array and then converting it to a matrix using np.asmatrix() function −
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)
This will produce the following result −
Converted Matrix: [[5 6] [7 8]]
Matrix Operations in NumPy
Once you have created a matrix, you can perform a wide range of matrix operations, such as addition, multiplication, transpose, inversion, and more.
Matrix Addition
Adding two matrices involves adding the corresponding elements. If two matrices have the same shape, you can add them together element-wise.
Example
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" −
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)
Following is the output of the above code −
[[ 6 8] [10 12]]
Matrix Multiplication
We can perform matrix multiplication using the following ways −
- Using the * operator
- Using the @ operator (Python 3.5+)
- Using np.dot() function
- Using the numpy.matmul() function
Unlike element-wise multiplication, matrix multiplication follows the linear algebra rules.
Example
In this example, we are multiplying two matrices using all the above given ways −
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)
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
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.
Example
In the following example, we are inverting a 2x2 matrix using np.linalg.inv() function. The output is a new matrix that, when multiplied by the original, results in the identity matrix −
import numpy as np matrix = np.array([[1, 2], [3, 4]]) inverse_matrix = np.linalg.inv(matrix) print(inverse_matrix)
After executing the above code, we get the following output −
[[-2. 1. ] [ 1.5 -0.5]]
Matrix Transpose
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.
Example
In the following example, we are transposing a 2x2 matrix using the ".T" attribute −
import numpy as np # Transpose of a matrix matrix = np.array([[1, 2], [3, 4]]) transposed = matrix.T print(transposed)
The result produced is as follows −
[[1 3] [2 4]]
Matrix Determinant
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.
Example
In this example, np.linalg.det() function computes the determinant of the given matrix −
import numpy as np # Compute the determinant matrix = np.array([[1, 2], [3, 4]]) det = np.linalg.det(matrix) print("Determinant:", det)
We get the output as shown below −
Determinant: -2.0000000000000004
Eigenvalues and Eigenvectors
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.
Example
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 −
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)
Following is the output obtained −
Eigenvalues: [3. 2.] Eigenvectors: [[0.89442719 0.70710678] [0.4472136 0.70710678]]
Singular Value Decomposition (SVD)
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.
Example
In the following example, we are performing singular value decomposition on a "2x2" matrix using np.linalg.svd() function. The result includes the U matrix, singular values, and the V matrix, which together represent the original matrix −
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)
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]]