溫馨提示×

python中怎么用numpy模塊創建矩陣

小億
238
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女