温馨提示×

python中怎么用numpy模块创建矩阵

小亿
102
2023-11-08 15:18:20
栏目: 编程语言

在Python中,可以使用numpy模块创建矩阵。下面是一些常用的方法:

  1. 使用numpy的array函数创建矩阵:
import numpy as np

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

输出:

[[1 2 3]
 [4 5 6]
 [7 8 9]]
  1. 使用numpy的zeros函数创建全零矩阵:
import numpy as np

matrix = np.zeros((3, 3))
print(matrix)

输出:

[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]
  1. 使用numpy的ones函数创建全一矩阵:
import numpy as np

matrix = np.ones((3, 3))
print(matrix)

输出:

[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]
  1. 使用numpy的eye函数创建单位矩阵:
import numpy as np

matrix = np.eye(3)
print(matrix)

输出:

[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
  1. 使用numpy的random函数创建随机矩阵:
import numpy as np

matrix = np.random.random((3, 3))
print(matrix)

输出类似于:

[[0.12345678 0.98765432 0.54321098]
 [0.87654321 0.23456789 0.98765432]
 [0.3456789  0.90123457 0.7654321 ]]

这些是使用numpy模块创建矩阵的一些常见方法,可以根据需要选择适合的方法创建所需的矩阵。

0