Flatten a Matrix in Numpy for Beginners – Numpy Tutorial

By | September 15, 2019

To flatten a numpy matrix, we have two methods.

Preliminaries

import numpy as np

Create a Matrix

matrix = np.array([[[3,4,5]],[[2,3,4]]])

The output is:

array([[[3, 4, 5]],

       [[2, 3, 4]]])

Flatten this matrix

Method 1: use ndarray.flatten() function

m1 = matrix.flatten()

The output is:

array([3, 4, 5, 2, 3, 4])

Method 2: use np.reshape() function

m2 = np.reshape(matrix,[-1])

The output is:

array([3, 4, 5, 2, 3, 4])

flatten a matrix in numpy

Leave a Reply

Your email address will not be published. Required fields are marked *