深度阅读

How to Convert NumPy Matrix to Array

作者
作者
2023年08月22日
更新时间
10.18 分钟
阅读时间
0
阅读量

There are several ways to convert a NumPy matrix to an array in Python. Here are a few examples:

  1. 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]
  1. 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]
  1. 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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。