在 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))

示例

Open Compiler
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))

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

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

更新时间: 2022 年 3 月 2 日

161 次浏览

开启你的职业生涯

通过完成课程获得认证

开始
广告