在 Python 中獲取陣列和標量的外積
若要獲取陣列和標量的外部積,請在 Python 中使用 numpy.outer() 方法。第一個引數 a 是第一個輸入向量。若輸入還不是一維的,則輸入會被拉平。第二個引數 b 是第二個輸入向量。若輸入還不是一維的,則輸入會被拉平。第三個引數 out 是儲存結果的位置。
給定兩個向量,a = [a0, a1, ..., aM] 和 b = [b0, b1, ..., bN],外積為 −
[[a0*b0 a0*b1 ... a0*bN ] [a1*b0 . [ ... . [aM*b0 aM*bN ]]
步驟
首先,匯入所需的庫 −
import numpy as np
使用 numpy.eye() 建立一個數組。此方法返回一個 2-D 陣列,其中對角線上的元素為 1,其他元素為 0 −
arr = np.eye(2)
val 是標量 −
val = 2
顯示陣列 −
print("Array...\n",arr)檢查資料型別 −
print("\nDatatype of Array...\n",arr.dtype)
檢查維度 −
print("\nDimensions of Array...\n",arr.ndim)檢查形狀 −
print("\nShape of Array...\n",arr.shape)
要獲取陣列和標量的外部積,請在 Python 中使用 numpy.outer() 方法 −
print("\nResult (Outer Product)...\n",np.outer(arr, val))示例
import numpy as np
# Create an array using numpy.eye(). This method returns a 2-D array with ones on the diagonal and zeros elsewhere.
arr = np.eye(2)
# The val is the scalar
val = 2
# Display the array
print("Array...\n",arr)
# Check the datatype
print("\nDatatype of Array...\n",arr.dtype)
# Check the Dimensions
print("\nDimensions of Array...\n",arr.ndim)
# Check the Shape
print("\nShape of Array...\n",arr.shape)
# To get the Outer product of an array and a scalar, use the numpy.outer() method in Python
print("\nResult (Outer Product)...\n",np.outer(arr, val))輸出
Array... [[1. 0.] [0. 1.]] Datatype of Array... float64 Dimensions of Array... 2 Shape of Array... (2, 2) Result (Outer Product)... [[2.] [0.] [0.] [2.]]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
SQL
Javascript
PHP