Flatten a matrix in Python using NumPy
In this tutorial, you will learn how to flatten a matrix in Python using NumPy
Introduction:
Here’s a short and straightforward example of how to flatten a matrix in Python using NumPy. This Python code demonstrates how to flatten a 2-dimensional matrix into a 1-dimensional array.
To flatten a matrix in Python To understand this, firstly we need to know what flattening is:
Flattening a matrix means converting a matrix with multiple rows and columns into a single row of elements.
Source of image: w3resource
Here’s a step-by-step procedure to do this:
Import the NumPy library:
NumPy (Numerical Python) is an open-source Python library that is used for numerical and scientific computing. It helps in working with arrays. We have to use this library to perform further operations.
import numpy as np
This line imports the NumPy library. NumPy supports numerous mathematical functions, matrices, and arrays.
Creating and Flattening the Matrix:
Creating a Matrix with ‘np.array( )’ :
To create a matrix in NumPy, we use the ‘np.array( )’ function which passes a list of lists as an argument. In which, each inner list represents a row of the matrix.
np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
This part creates a 2D NumPy array (matrix) with the specified elements.
The matrix looks like this:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Flattening the Matrix with ‘.flatten( )’ :
Next, flattening a matrix means converting it from a two-dimensional (or multi-dimensional) array into a one-dimensional array. This operation concatenates all the rows of the matrix into a single row (1D array).
flattened_matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]).flatten()
.flatten( ) : This method is called on the 2D array. It converts the 2D matrix into a 1D array by flattening it, resulting in:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Printing the Flattened Matrix:
Finally, we have to print the flattened matrix by using the general print statement.
print(flattened_matrix)
This will print the flattened matrix.
Complete Code:
import numpy as np # Flatten the matrix flattened_matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]).flatten() # Print the flattened matrix print(flattened_matrix)
Output:
[1 2 3 4 5 6 7 8 9]
The matrix can easily be flattened and printed using this simple and straightforward approach.
For a more in-depth explanation using additional functions and examples on how to flatten a matrix in Python using NumPy, you can refer to this:
You may also refer to and learn:
- Delete a row from a NumPy matrix in Python
- Convert a Matrix to a Sparse Matrix in C++
- Matrix inversion without NumPy in Python
- Check whether a matrix is sparse matrix or not in Python
Leave a Reply