向量-向量乘法以创建矩阵 [英] Vector-vector multiplication to create a matrix

查看:133
本文介绍了向量-向量乘法以创建矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个IDL用户,正在缓慢地切换到numpy/scipy,并且在IDL中我经常执行一项操作,但是无法用numpy进行复制:

I am an IDL user slowly switching to numpy/scipy, and there is an operation that I do extremely often in IDL but cannot manage to reproduce with numpy:

IDL> a = [2., 4]
IDL> b = [3., 5]
IDL> print,a # b
      6.00000      12.0000
      10.0000      20.0000

我什至不确定此操作的名称(英语不是我的主要语言).也许很明显如何在numpy中执行此操作,但是我找不到简单的方法.

I'm not even sure of about the name of this operation (English is not my primary language). Maybe it is obvious how to do it in numpy, but I could not find a simple way.

谢谢.

-亚瑟;

推荐答案

这称为外部产品两个向量.您可以使用 np.outer :

This is known as the outer product of two vectors. You could use np.outer:

import numpy as np

a = np.array([2, 4])
b = np.array([3, 5])
c = np.outer(a, b)

print(c)
# [[ 6 10]
#  [12 20]]

假设两个输入都是numpy数组(而不是Python列表等),则还可以将标准*运算符与

Assuming that both of your inputs are numpy arrays (rather than Python lists etc.) you also could use the standard * operator with broadcasting:

# you could also replace np.newaxis with None for brevity (see below)
d = a[:, np.newaxis] * b[np.newaxis, :]

您还可以使用 np.dot 结合广播:

You could also use np.dot in combination with broadcasting:

e = np.dot(a[:, None], b[None, :])

另一个鲜为人知的选择是使用np.multiply ufunc的="nofollow"> .outer 方法:

Another lesser-known option is to use the .outer method of the np.multiply ufunc:

f = np.multiply.outer(a, b)

我个人会在广播中使用np.outer*.

Personally I would either use np.outer or * with broadcasting.

这篇关于向量-向量乘法以创建矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆