简体   繁体   English

在 Numpy 中将列向量和行向量相乘

[英]Multiplying column and row vectors in Numpy

I'd like to multiply two vectors, one column (ie, (N+1)x1), one row (ie, 1x(N+1)) to give a (N+1)x(N+1) matrix.我想将两个向量、一列(即 (N+1)x1)、一行(即 1x(N+1))相乘得到一个 (N+1)x(N+1) 矩阵。 I'm fairly new to Numpy but have some experience with MATLAB, this is the equivalent code in MATLAB to what I want in Numpy:我对 Numpy 相当陌生,但对 MATLAB 有一些经验,这是 MATLAB 中与我在 Numpy 中想要的等效代码:

n = 0:N; 
xx = cos(pi*n/N)';
T = cos(acos(xx)*n');

in Numpy I've tried:在 Numpy 我试过:

import numpy as np
n = range(0,N+1)

pi = np.pi
xx = np.cos(np.multiply(pi / float(N), n))

xxa = np.asarray(xx)
na = np.asarray(n)
nd = np.transpose(na)

T = np.cos(np.multiply(np.arccos(xxa),nd))

I added the asarray line after I noticed that without it Numpy seemed to be treating xx and n as lists.在我注意到没有它 Numpy 似乎将 xx 和 n 视为列表后,我添加了 asarray 行。 np.shape(n) , np.shape(xx) , np.shape(na) and np.shape(xxa) gives the same result: (100001L,) np.shape(n) , np.shape(xx) , np.shape(na)np.shape(xxa)给出相同的结果: (100001L,)

np.multiply only does element by element multiplication. np.multiply只做逐个元素的乘法。 You want an outer product.你想要一个外部产品。 Use np.outer :使用np.outer

np.outer(np.arccos(xxa), nd)

If you want to use NumPy similar to MATLAB, you have to make sure that your arrays have the right shape.如果您想使用类似于 MATLAB 的 NumPy,您必须确保您的数组具有正确的形状。 You can check the shape of any NumPy array with arrayname.shape and because your array na has shape (4,) instead of (4,1) , the transpose method is effectless and multiply calculates the dot product.您可以使用arrayname.shape检查任何 NumPy 数组的形状,并且因为您的数组na具有形状(4,)而不是(4,1)transpose方法无效, multiply计算点积。 Use arrayname.reshape(N+1,1) resp.使用arrayname.reshape(N+1,1)响应。 arrayname.reshape(1,N+1) to transform your arrays: arrayname.reshape(1,N+1)来转换你的数组:

import numpy as np

n = range(0,N+1)
pi = np.pi
xx = np.cos(np.multiply(pi / float(N), n))

xxa = np.asarray(xx).reshape(N+1,1)
na = np.asarray(n).reshape(N+1,1)
nd = np.transpose(na)

T = np.cos(np.multiply(np.arccos(xxa),nd))

Since Python 3.5, you can use the @ operator for matrix multiplication.从 Python 3.5 开始,您可以使用@运算符进行矩阵乘法。 So it's a walkover to get code that's very similar to MATLAB:因此,获得与 MATLAB 非常相似的代码是一个简单的过程:

import numpy as np

n = np.arange(N + 1).reshape(N + 1, 1)   
xx = np.cos(np.pi * n / N)
T = np.cos(np.arccos(xx) @ n.T)

Here nT denotes the transpose of n.这里nT表示 n 的转置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM