Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

หาผลคูณนอก (Outer product) ของสองอาร์เรย์ใน Python ด้วย numpy.outer()

เพื่อหาผลคูณนอก (Outer product) ของสองเวกเตอร์ ให้ใช้ numpy.outer() พารามิเตอร์ a และ b คือเวกเตอร์อินพุต จะถูก flatten หากไม่ใช่ 1 มิติ ผลลัพธ์คือเมทริกซ์ที่แต่ละองค์ประกอบคือผลคูณของคู่จาก a และ b

ขั้นตอนการใช้งาน

import numpy as np

สร้างสองอาร์เรย์ 1 มิติ

arr1 = np.array([5, 10, 15])
arr2 = np.array([20, 25, 30])
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)

คำนวณ Outer product

print("\nResult (Outer Product)...\n", np.outer(arr1, arr2))

โค้ดตัวอย่างสมบูรณ์

import numpy as np

arr1 = np.array([5, 10, 15])
arr2 = np.array([20, 25, 30])
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)
print("\nResult (Outer Product)...\n", np.outer(arr1, arr2))

ผลลัพธ์ที่คาดหวัง

Array1...
[ 5 10 15]
Array2...
[20 25 30]
Dimensions of Array1...
1
Dimensions of Array2...
1
Shape of Array1...
(3,)
Shape of Array2...
(3,)
Result (Outer Product)...
[[100 125 150]
 [200 250 300]
 [300 375 450]]