Flatten a Matrix in Python using NumPy
Flattening means converting a 2D matrix into a 1D array. In NumPy, this is done using the ndarray.flatten() function.

flatten() Function
The flatten() function creates a copy of the array and returns it in 1D form.
Example 1: Flattening a 2×3 Matrix
import numpy as np
matrix = np.array([[10, 20, 30], [40, 50, 60]])
flat = matrix.flatten()
print(flat)
Output
[10 20 30 40 50 60]
The values are read row by row and stacked into a 1D array.
Syntax
numpy_array.flatten(order='C')
Parameters:
- order='C' Flatten in row-major order (default).
- order='F' Flatten in column-major order.
- order='A' Flatten in column-major if memory is Fortran-contiguous, else row-major.
- order='K' Flatten in the order elements occur in memory.
Return: A new flattened 1D array.
Example 2: Flattening a 3×2 Matrix
import numpy as np
matrix = np.array([[6, 9], [8, 5], [18, 21]])
flat = matrix.flatten()
print(flat)
Output
[ 6 9 8 5 18 21]
Again, elements are read row by row and merged into 1D.
Example 3: Flatten with order Parameter
import numpy as np
matrix = np.array([[6, 9, 12],
[8, 5, 2],
[18, 21, 24]])
flat = matrix.flatten(order='A')
print(flat)
Output
[ 6 9 12 8 5 2 18 21 24]
Here, since the array is stored in row-major order, the result is the same as 'C'.