How to Flatten a Matrix using numpy in Python?


In this article, we will show you how to flatten a matrix using the NumPy library in python.

numpy.ndarray.flatten() function

The numpy module includes a function called numpy.ndarray.flatten() that returns a one-dimensional copy of the array rather than a two-dimensional or multi-dimensional array.

In simple words, we can say that it flattens a matrix to 1-Dimension.

Syntax

ndarray.flatten(order='C')

Parameters

order − 'C', 'F', 'A', 'K' (optional)

  • When we set the order parameter to 'C,' the array is flattened in row-major order.

  • When the 'F' is set, the array is flattened in column-major order.

  • Only when 'a' is Fortran contiguous in memory and the order parameter is set to 'A' is the array flattened in column-major order. The final order is 'K,' which flattens the array in the same order that the elements appeared in memory. This parameter is set to 'C' by default.

Return Value − Returns a flattened 1-D matrix

Method 1 − Flattening 2x2 Numpy Matrix of np.array() type

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Use the import keyword, to import the numpy module with an alias name(np).

  • Use the numpy.array() function(returns a ndarray. The ndarray is an array object that satisfies the given requirements), for creating a numpy array by passing the 2-Dimensional array(2rows, 2columns) as an argument to it.

  • Print the given input 2-Dimensional matrix.

  • Apply flatten() function (flattens a matrix to 1-Dimension) of the numpy module on the input matrix to flatten the input 2D matrix to a one-dimensional matrix.

  • Print the resultant flattened matrix of an input matrix.

Example

The following program flattens the given input 2-Dimensional matrix to a 1-Dimensional matrix using the flatten()function and returns it −

# importing numpy module with an alias name import numpy as np # creating a 2-Dimensional(2x2) numpy matrix inputMatrix = np.array([[3, 5], [4, 8]]) # printing the input 2D matrix print("The input numpy matrix:") print(inputMatrix) # flattening the 2D matrix to one-dimensional matrix flattenMatrix = inputMatrix.flatten() # printing the resultant flattened matrix print("Resultant flattened matrix:") print(flattenMatrix)

Output

On executing, the above program will generate the following output −

The input numpy matrix:
[[3 5]
[4 8]]
Resultant flattened matrix:
[3 5 4 8]

Method 2 − Flattening using reshape() function

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Use the numpy.array() function(returns a ndarray. The ndarray is an array object that satisfies the given requirements), for creating a numpy array by passing the 4-Dimensional array(4rows, 4columns) as an argument to it.

  • Print the given input 4-Dimensional matrix.

  • Calculate the number of elements of the matrix by multiplying the length of the NumPy array with itself. Here these values give the number of columns required.

  • Use the reshape() function(reshapes an array without affecting its data) to reshape the array and flatten the input matrix(4D) to a one-dimensional matrix.

  • Print the resultant flattened matrix of an input matrix.

Example

The following program flattens the given input 4-Dimensional matrix to a 1-Dimensional matrix using reshape() function and returns it −

# importing numpy module with an alias name import numpy as np # creating a 4-Dimensional(4x4) numpy matrix inputMatrix = np.array([[1, 2, 3, 97], [4, 5, 6, 98], [7, 8, 9, 99], [10, 11, 12, 100]]) # Getting the total Number of elements of the matrix matrixSize = len(inputMatrix) * len(inputMatrix) # printing the input 4D matrix print("The input numpy matrix:") print(inputMatrix) # reshaping the array and flattening the 4D matrix to a one-dimensional matrix # here (1,matrixSize(16)) says 1 row and 16 columns(Number of elements) flattenMatrix= np.reshape(inputMatrix, (1, matrixSize)) # printing the resultant flattened matrix print("Resultant flattened matrix:") print(flattenMatrix)

Output

On executing, the above program will generate the following output −

The input numpy matrix:
[[  1   2   3  97]
 [  4   5   6  98]
 [  7   8   9  99]
 [ 10  11  12 100]]
Resultant flattened matrix:
[[  1   2   3  97   4   5   6  98   7   8   9  99  10  11  12 100]]

Method 3 − Flattening 4x4 Numpy Matrix of np.matrix() type

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Use the numpy.matrix() function(returns a matrix from a string of data or an array-like object. The resulting matrix is a specialized 4D array), for creating a numpy matrix by passing the 4-Dimensional array(4 rows, 4 columns) as an argument to it.

  • Print the resultant flattened matrix of an input matrix.

Example

The following program flattens the given input 4-Dimensional matrix to a 1-Dimensional matrix using the flatten()function and returns it −

# importing NumPy module with an alias name import numpy as np # creating a NumPy matrix (4x4 matrix) using matrix() method inputMatrix = np.matrix('[11, 1, 8, 2; 11, 3, 9 ,1; 1, 2, 3, 4; 9, 8, 7, 6]') # printing the input 4D matrix print("The input numpy matrix:") print(inputMatrix) # flattening the 4D matrix to one-dimensional matrix flattenMatrix = inputMatrix.flatten() # printing the resultant flattened matrix print("Resultant flattened matrix:") print(flattenMatrix)

Output

On executing, the above program will generate the following output −

The input numpy matrix:
[[11  1  8  2]
 [11  3  9  1]
 [ 1  2  3  4]
 [ 9  8  7  6]]
Resultant flattened matrix:
[[11  1  8  2 11  3  9  1  1  2  3  4  9  8  7  6]]

Conclusion

In this article, we learned how to flatten the matrix in python using three different examples. We learned how to take a matrix in Numpy using two different methods: numpy.array() and NumPy.matrix(). We also learned how to flatten a matrix using the reshape function.

Updated on: 31-Oct-2022

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements