Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying column and row vectors in Numpy

I'd like to multiply two vectors, one column (i.e., (N+1)x1), one row (i.e., 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,)

like image 230
Josh Pinto Avatar asked Mar 20 '15 09:03

Josh Pinto


2 Answers

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 n.T denotes the transpose of n.

like image 83
joni Avatar answered Sep 29 '22 22:09

joni


np.multiply only does element by element multiplication. You want an outer product. Use np.outer:

np.outer(np.arccos(xxa), nd)
like image 31
Brionius Avatar answered Sep 29 '22 23:09

Brionius