Python에서 두 1차원 배열의 외적(Outer Product)을 구하려면 numpy.outer() 메서드를 사용하면 됩니다. 이 함수는 세 가지 매개변수를 받습니다.
- a – 첫 번째 입력 벡터입니다. 입력이 이미 1차원이 아니라면 자동으로 평탄화(flatten)됩니다.
- b – 두 번째 입력 벡터입니다. 마찬가지로 1차원이 아니면 평탄화됩니다.
- 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
array() 메서드를 사용해 두 개의 1차원 NumPy 배열을 생성합니다.
arr1 = np.array([5, 10, 15]) arr2 = np.array([20, 25, 30])
생성한 배열을 화면에 출력합니다.
print("Array1...\n", arr1)
print("\nArray2...\n", arr2)두 배열의 차원(ndim)을 확인합니다.
print("\nDimensions of Array1...\n", arr1.ndim)
print("\nDimensions of Array2...\n", arr2.ndim)두 배열의 형태(shape)를 확인합니다.
print("\nShape of Array1...\n", arr1.shape)
print("\nShape of Array2...\n", arr2.shape)마지막으로 numpy.outer() 메서드를 사용해 두 1차원 배열의 외적을 계산합니다.
print("\nResult (Outer Product)...\n", np.outer(arr1, arr2))전체 예제 코드
import numpy as np
# array() 메서드를 사용해 두 개의 1차원 NumPy 배열 생성
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)
# numpy.outer() 메서드로 두 1차원 배열의 외적 계산
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]]
위 결과에서 볼 수 있듯이, 크기가 각각 3인 두 1차원 배열의 외적은 3×3 크기의 2차원 행렬로 반환됩니다. 결과 행렬의 각 요소는 첫 번째 배열의 요소와 두 번째 배열의 요소를 곱한 값입니다. 예를 들어 결과의 첫 번째 행은 arr1의 첫 번째 요소 5에 arr2의 각 요소(20, 25, 30)를 곱한 값인 100, 125, 150으로 구성됩니다.