Convert Matrix to Array in Numpy

  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

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]
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python Numpy

  • Find the First Index of Element in Numpy Array
  • Add Row to Matrix in Numpy