Home > Backend Development > Python Tutorial > How to flatten a matrix in Python using numpy?

How to flatten a matrix in Python using numpy?

WBOY
Release: 2023-08-20 16:37:13
forward
1139 people have browsed it

How to flatten a matrix in Python using numpy?

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 terms, we can say that it flattens the matrix into 1 dimension.

grammar

ndarray.flatten(order='C')
Copy after login

parameter

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

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

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

  • The array is expanded in column major order only if 'a' is Fortran contiguous in memory and the order parameter is set to 'A'. The final order is 'K', which unwraps the array in the same order as the elements appear 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)

The following are the algorithms/steps to perform the required task:

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

  • Use the numpy.array() function (returns an ndarray. An ndarray is an array object that meets the given requirements), by passing a 2-dimensional array (2 rows, 2 columns) as a parameter Give it to create a numpy array.

  • Print the given two-dimensional matrix.

  • Apply the flatten() function of the numpy module (flatten the matrix into one dimension) on the input matrix to flatten the input two-dimensional matrix into a one-dimensional matrix.

  • Print the resulting flattened matrix of the 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)
Copy after login

Output

When executed, the above program will generate the following output -

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

Method 2 − Flattening using reshape() function

Algorithm (Steps)

The following are the algorithms/steps to perform the required 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 4-dimensional matrix.

  • Calculate the number of elements of a matrix by multiplying the length of the NumPy array by itself. These values ​​represent the required number of columns.

  • 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 resulting flattened matrix of the input matrix.

Example

The following program uses the reshape() function to flatten the given 4-dimensional matrix into a 1-dimensional matrix and returns the result -

# 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)
Copy after login

Output

When executed, 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]]
Copy after login

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

The Chinese translation is:

Method 3 - Flattening the 4x4 Numpy matrix of np.matrix() type

Algorithm (Steps)

The following are the algorithms/steps to perform the required task:

  • Use the numpy.matrix() function (returns a matrix from a data string or array-like object. The resulting matrix is ​​a specialized 4D array), by converting the 4-dimensional array ( 4 rows, 4 columns) as arguments to create a numpy matrix.

  • Print the resulting flattened matrix of the input matrix.

Example

The following program uses the flatten() function to flatten a given 4-dimensional matrix into a 1-dimensional matrix and returns the result -

# 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)
Copy after login

Output

When executed, 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]]
Copy after login

Conclusion

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

The above is the detailed content of How to flatten a matrix in Python using numpy?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template