在 Python 中獲取兩個陣列的克羅內克積
要獲得兩個陣列的克羅內克積,請在 Python Numpy 中使用 numpy.kron() 方法。計算克羅內克積,即一個合成數組,由第二個陣列的塊組成,並按第一個陣列進行縮放。
該函式假設 a 和 b 的維度相同,如果必要,則在最小維中新增 1。如果 a.shape = (r0,r1,..,rN) 和 b.shape = (s0,s1,...,sN),克羅內克積的形狀為 (r0*s0, r1*s1, ..., rN*SN)。元素是 a 和 b 中元素的乘積,明確按 − 組織
kron(a,b)[k0,k1,...,kN] = a[i0,i1,...,iN] * b[j0,j1,...,jN]
步驟
首先,匯入所需的庫 −
import numpy as np
使用 array() 方法建立兩個 numpy 陣列 −
arr1 = np.array([1, 10, 100]) arr2 = np.array([5, 6, 7])
顯示陣列 −
print("Array1...\n",arr1)
print("\nArray2...\n",arr2)檢查兩個陣列的維度 −
print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)檢查兩個陣列的形狀 −
print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)要獲得兩個陣列的克羅內克積,請在 Python 中使用 numpy.kron() 方法 −
print("\nResult (Kronecker product)...\n",np.kron(arr1, arr2))
示例
import numpy as np
# Creating two numpy arrays using the array() method
arr1 = np.array([1, 10, 100])
arr2 = np.array([5, 6, 7])
# Display the arrays
print("Array1...\n",arr1)
print("\nArray2...\n",arr2)
# Check the Dimensions of both the array
print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)
# Check the Shape of both the array
print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)
# To get the Kronecker product of two arrays, use the numpy.kron() method in Python Numpy
print("\nResult (Kronecker product)...\n",np.kron(arr1, arr2))輸出
Array1... [ 1 10 100] Array2... [5 6 7] Dimensions of Array1... 1 Dimensions of Array2... 1 Shape of Array1... (3,) Shape of Array2... (3,) Result (Kronecker product)... [ 5 6 7 50 60 70 500 600 700]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP