简体   繁体   中英

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

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

in Numpy I've tried:

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. np.shape(n) , np.shape(xx) , np.shape(na) and np.shape(xxa) gives the same result: (100001L,)

np.multiply only does element by element multiplication. You want an outer product. Use 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. 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. Use arrayname.reshape(N+1,1) resp. arrayname.reshape(1,N+1) to transform your arrays:

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. So it's a walkover to get code that's very similar to 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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