Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python에서 배열과 스칼라의 외적 가져오기

<시간/>

배열과 스칼라의 외부 곱을 얻으려면 Python에서 numpy.outer() 메서드를 사용합니다. 첫 번째 매개변수 a는 첫 번째 입력 벡터입니다. 이미 1차원이 아닌 경우 입력이 평면화됩니다. 두 번째 매개변수 b는 두 번째 입력 벡터입니다. 이미 1차원이 아닌 경우 입력이 평면화됩니다. 3번째 매개변수 출력은 결과가 저장되는 위치입니다.

두 벡터 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()를 사용하여 배열을 만듭니다. 이 메서드는 대각선에 1이 있고 다른 곳에 0이 있는 2차원 배열을 반환합니다. -

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.]]