How to Convert Matrix to Array in NumPy

Manav Narula Feb 02, 2024
  1. Use the numpy.flatten() Function to Convert a Matrix to an Array in NumPy
  2. Use the numpy.ravel() Function to Convert a Matrix to an Array in NumPy
  3. Use the numpy.reshape() Function to Convert a Matrix to an Array in NumPy
How to Convert Matrix to Array in NumPy

NumPy has many functions and classes available for performing different operations on matrices.

In this tutorial, we will learn how to convert a matrix to an array in NumPy.

Use the numpy.flatten() Function to Convert a Matrix to an Array in NumPy

The flatten() takes an N-Dimensional array and converts it to a single dimension array.

It works only with ndarray objects.

It can convert a matrix to an array as shown below.

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr.flatten())

Output:

[1 2 3 4 5 6 7 8 9]

Note that if we work with a matrix type object, we have to use the asarray() function to convert it to an array and then use the flatten() function. It can be done for all the methods.

For example,

import numpy as np

arr = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
arr_d = (np.asarray(arr)).flatten()
print(arr_d)

Output:

[1 2 3 4 5 6 7 8 9]

Use the numpy.ravel() Function to Convert a Matrix to an Array in NumPy

The ravel() function works exactly like the flatten() function with a few notable differences. Both are used to transform N-Dimensional arrays to single dimension arrays.

However, the ravel() function is a library function and can also work on objects like a list of arrays. The flatten() returns a copy of the original, whereas ravel() always returns a view of the original whenever possible.

In the following code, we will use this function to convert a matrix.

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr.ravel())

Output:

[1 2 3 4 5 6 7 8 9]

Use the numpy.reshape() Function to Convert a Matrix to an Array in NumPy

The reshape() modified the overall shape of the array without altering its contents. If we assign the new shape of a matrix as -1, we get a one-dimensional array.

For example,

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr.reshape(-1))

Output:

[1 2 3 4 5 6 7 8 9]
Author: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn