• Post author:
  • Post category:NumPy / Python
  • Post last modified:March 27, 2024
  • Reading time:15 mins read
You are currently viewing How to Convert NumPy Matrix to Array

Convert the NumPy matrix to an array can be done by taking an N-Dimensional array (matrix) and converting it to a single dimension array. There are various ways to transform the matrix to an array in NumPy, for example by using flatten(), ravel() and reshape() functions. In this article, I will explain how to convert a matrix to an array in different ways with examples.

Advertisements

1. Quick Examples of Convert Matrix to Array

If you are in a hurry, below are some quick examples of how to convert the NumPy matrix to an array.


# Quick examples of convert matrix to array

# Example 1: Using flatten() function
# Convert the 2D array to a 1D array
result = arr.flatten()

# Example 2: Using ravel() function
# Convert the matrix to a 1D array
result = np.ravel(arr)

# Example 3: Using reshape()
# convert the matrix to a 1D array
result = np.reshape(arr, -1)

# Example 4: Convert numpy matrix to array 
# Use reshape()
result = arr.reshape(-1)

2. Convert NumPy Matrix to Array Using flatten()

We can use numpy.flatten() function to convert the matrix to an array. It takes all N elements of the matrix placed into a single-dimension array.

2.1 Syntax of flatten()

Following is the syntax of the numpy.flatten() function.


# Syntax of flatten()
ndarray.flatten(order='C')

Following are the parameters of the flatten() function.

  • order – {‘C’, ‘F’, ‘A’, ‘K’}, optional: ‘C’: means to flatten in row-major using C-style order. ‘F’: means to flatten in column-major (Fortran- style) order. ‘A’: means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise. K’: means to flatten an in the order the elements occur in memory. By default, the ‘C’ index order is used.

2.2 NumPy flatten() Example

The NumPy flatten() function is used to transform a multi-dimensional array into a one-dimensional array. For instance, the flatten() function has transformed the 2D array into a 1D array, making it easier to work with in certain situations where you need a flat array.


# Import numpy
import numpy as np

# Create NumPy 2-D array
arr = np.array([[2,4,6],[8,10,12],[14,16,18]])
print("Original 2D Array:\n",arr)

# Using flatten() function
# Convert the 2D array to a 1D array
result = arr.flatten()
print("After converting the numpy matrix to an array:\n",result)

Yields below output.

convert numpy matrix array

3. Convert NumPy Matrix to Array Using ravel()

The numpy.ravel() function is used to create a contiguous flattened array from a given input array. This function returns a flattened one-dimensional array, meaning it collapses the input array into a flat, contiguous sequence.

3.1 Syntax of ravel()

Following is the syntax of the numpy.ravel() function.


# Syntax of ravel()
numpy.ravel(arr, order='C')

Following are the parameters of the ravel() function.

  • arr – Input array. The array elements are read in the order specified by the order parameter and packed as a 1-D array.
  • order – {‘C’, ‘F’, ‘A’, ‘K’}, optional to read the elements of a using this index order. ‘C’ means to index the elements in row-major using C-style order. ‘F’: means to index the elements in column-major i.e. using Fortran-like index order. ‘A’: means to read the elements in Fortran-like index order if a is Fortran contiguous in memory, C-like order otherwise. ‘K’ means to read the elements in the order they occur in memory, except for reversing the data when strides are negative. By default, the ‘C’ index order is used.

3.2 NumPy ravel() Example

Alternatively, you can use the ravel() function to convert a matrix into a one-dimensional array. For example, the ravel() function is applied to the arr variable, converting the 2D matrix into a 1D array. The resulting result contains the elements of the matrix in a one-dimensional sequence.


import numpy as np

# Create NumPy 2-D array
arr = np.array([[2,4,6],[8,10,12],[14,16,18]])
print("Original 2D Array:\n",arr)

# Using ravel() function
# Convert the matrix to a 1D array
result = np.ravel(arr)
print("After converting the numpy matrix to an array:\n",result)

Yields the same output as above.

4. Convert NumPy Matrix to Array with reshape()

You can also use the reshape() function to convert the matrix into a different shape, including flattening it into a one-dimensional array.

In the below example, the reshape() function is applied to the arr variable, with the target shape specified as -1. The -1 in the target, the shape indicates that NumPy should automatically calculate the size of that dimension, which effectively flattens the matrix into a one-dimensional array.


import numpy as np

# Create NumPy 2-D array
arr = np.array([[2,4,6],[8,10,12],[14,16,18]])
print("Original 2D Array:\n",arr)

# Using reshape()
# convert the matrix to a 1D array
result = np.reshape(arr, -1)
print("After converting the numpy matrix to an array:\n",result)

# Convert numpy matrix to array 
# Use reshape()
result = arr.reshape(-1)
print("After converting the numpy matrix to an array:\n",result)

Yields the same output as above.

Frequently Asked Questions

What is the difference between a NumPy matrix and a NumPy array?

In NumPy, a matrix is a specialized 2D array that has some additional features compared to a regular 2D array. Matrices are strictly 2-dimensional, while arrays can have any number of dimensions. However, it is recommended to use arrays over matrices because arrays are more versatile and offer a wider range of operations and compatibility with other NumPy functions.

What is the ravel() function in NumPy, and how can I use it to convert a matrix to an array?

The ravel() function in NumPy is used to flatten a multi-dimensional array into a one-dimensional array. It returns a flattened one-dimensional array containing the elements of the input array in a contiguous manner. This function does not modify the original array; instead, it creates a new one-dimensional array with a copy of the input data.

Can I convert a NumPy matrix to a one-dimensional array using the reshape() function?


You can convert a NumPy matrix to a one-dimensional array using the reshape() function. The reshape() function in NumPy is used to change the shape of an array, including flattening it into a one-dimensional array.

Can I convert a NumPy matrix with non-numeric elements to an array?

You can convert a NumPy matrix with non-numeric elements to an array. NumPy arrays can store elements of various data types, including non-numeric data types like strings. When you convert a NumPy matrix with non-numeric elements to an array, NumPy will automatically handle the data type conversion as needed.

Can I convert a sparse matrix to a NumPy array?

You can convert a sparse matrix to a NumPy array using the toarray() method provided by libraries like SciPy. SciPy is a library built on top of NumPy that provides additional functionality for scientific computing, including support for sparse matrices.

Conclusion

In this article, I have explained how to convert a matrix to an array by using the NumPy flatten(), ravel(), and reshape() functions with examples.

Happy Learning!!

References

Malli

Malli is an experienced technical writer with a passion for translating complex Python concepts into clear, concise, and user-friendly articles. Over the years, he has written hundreds of articles in Pandas, NumPy, Python, and takes pride in ability to bridge the gap between technical experts and end-users.