How to Convert NumPy Matrix to Array
Published on Aug. 22, 2023, 12:16 p.m.
There are several ways to convert a NumPy matrix to an array in Python. Here are a few examples:
- Using the
numpy.ndarray.flatten()
function: This will convert the matrix into a 1-dimensional array. Here’s an example:
import numpy as np
M = np.matrix([[1, 2], [3, 4]])
A = np.ndarray.flatten(M)
print(A)
Output:
[1 2 3 4]
- Using the
numpy.ravel()
function: This will also convert the matrix into a 1-dimensional array, but with a different order if you provide the “F” order. Here’s an example:
import numpy as np
M = np.matrix([[1, 2], [3, 4]])
A = np.ravel(M, order='C')
print(A)
Output:
[1 2 3 4]
- Using the
numpy.asarray()
function: This will convert the matrix into an array without flattening it. Here’s an example:
import numpy as np
M = np.matrix([[1, 2], [3, 4]])
A = np.asarray(M)
print(A)
Output:
[[1 2]
[3 4]]
You can use whatever method that suits your needs best, depending on how you want to use the resulting array.