在Python中获取数组和标量的外积

在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()创建一个数组。这个方法返回一个二维数组,对角线上元素为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))

示例

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

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程