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

การหาผลคูณนอก (outer product) ของอาร์เรย์และสเกลาร์ใน Python


ภาพรวม

ใช้ numpy.outer() เพื่อหาผลคูณนอกของอาร์เรย์กับสเกลาร์ อินพุตจะถูกทำให้เป็น 1 มิติอัตโนมัติ

สูตร outer product

สำหรับเวกเตอร์ a = [a0, a1, ..., aM] และ b = [b0, b1, ..., bN]:

[[a0*b0 a0*b1 ... a0*bN]
 [a1*b0 a1*b1 ... a1*bN]
 ...
 [aM*b0 aM*b1 ... aM*bN]]

ขั้นตอนการทำงาน

  1. นำเข้าไลบรารี
    import numpy as np
    
  2. สร้างเมทริกซ์เอกลักษณ์และสเกลาร์
    arr = np.eye(2)
    val = 2
    
  3. ตรวจสอบคุณสมบัติ
    print("อาร์เรย์...\n", arr)
    print("\nชนิดข้อมูล...\n", arr.dtype)
    print("\nมิติ...\n", arr.ndim)
    print("\nรูปร่าง...\n", arr.shape)
    
  4. คำนวณ outer product
    print("\nผลลัพธ์ (Outer Product)...\n", np.outer(arr, val))
    

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

import numpy as np

arr = np.eye(2)
val = 2

print("อาร์เรย์...\n", arr)
print("\nชนิดข้อมูลของอาร์เรย์...\n", arr.dtype)
print("\nมิติของอาร์เรย์...\n", arr.ndim)
print("\nรูปร่างของอาร์เรย์...\n", arr.shape)

print("\nผลลัพธ์ (Outer Product)...\n", np.outer(arr, val))

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

อาร์เรย์...
 [[1. 0.]
 [0. 1.]]
ชนิดข้อมูลของอาร์เรย์...
 float64
มิติของอาร์เรย์...
 2
รูปร่างของอาร์เรย์...
 (2, 2)
ผลลัพธ์ (Outer Product)...
 [[2.]
 [0.]
 [0.]
 [2.]]