Python 中的矩陣操作


我們可以使用 Numpy 庫輕鬆地在 Python 中執行矩陣操作。NumPy 是一個 Python 包。它代表“數值 Python”。它是一個由多維陣列物件和一系列用於處理陣列的例程組成的庫。使用 NumPy,可以對陣列執行數學和邏輯運算。

安裝和匯入 Numpy

要安裝 Numpy,請使用 pip −

pip install numpy

匯入 Numpy −

import numpy

加、減、乘、除矩陣

我們將使用以下 Numpy 方法來進行矩陣操作 −

  • numpy.add() − 加兩個矩陣

  • numpy.subtract() − 減去兩個矩陣

  • numpy.divide() − 除以兩個矩陣

  • numpy.multiply() − 乘以兩個矩陣

我們現在來看看程式碼 −

示例

import numpy as np # Two matrices mx1 = np.array([[5, 10], [15, 20]]) mx2 = np.array([[25, 30], [35, 40]]) print("Matrix1 =\n",mx1) print("\nMatrix2 =\n",mx2) # The addition() is used to add matrices print ("\nAddition of two matrices: ") print (np.add(mx1,mx2)) # The subtract() is used to subtract matrices print ("\nSubtraction of two matrices: ") print (np.subtract(mx1,mx2)) # The divide() is used to divide matrices print ("\nMatrix Division: ") print (np.divide(mx1,mx2)) # The multiply()is used to multiply matrices print ("\nMultiplication of two matrices: ") print (np.multiply(mx1,mx2))

輸出

Matrix1 =
 [[ 5 10]
 [15 20]]

Matrix2 =
[[25 30]
 [35 40]]

Addition of two matrices:
[[30 40]
 [50 60]]

Subtraction of two matrices:
[[-20 -20]
 [-20 -20]]

Matrix Division:
[[0.2 0.33333333]
 [0.42857143 0.5 ]]

Multiplication of two matrices:
[[125 300]
 [525 800]]

矩陣元素求和

使用 sum() 方法來求和 −

示例

import numpy as np # A matrix mx = np.array([[5, 10], [15, 20]]) print("Matrix =\n",mx) print ("\nThe summation of elements=") print (np.sum(mx)) print ("\nThe column wise summation=") print (np.sum(mx,axis=0)) print ("\nThe row wise summation=") print (np.sum(mx,axis=1))

輸出

Matrix =
 [[ 5 10]
 [15 20]]

The summation of elements=
50

The column wise summation=
[20 30]

The row wise summation=
[15 35]

轉置矩陣

使用 .T 屬性來求矩陣的轉置 −

示例

import numpy as np # A matrix mx = np.array([[5, 10], [15, 20]]) print("Matrix =\n",mx) print ("\nThe Transpose =") print (mx.T)

輸出

Matrix =
 [[ 5 10]
 [15 20]]

The Transpose =
[[ 5 15]
 [10 20]]

更新於: 2022 年 8 月 11 日

15K+ 次檢視

開啟您的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.