3

I have a numpy array vector_a of shape (3,1). If I multiply it with a vector_b of shape (1,3) I get a result of shape (3,3).

Now, vector_b is actually an (3,N) numpy array of column vectors. I want to multiply each of these column vectors by vector_a to produce N 3x3 matrices, result of shape (N,3,3)

I have done the following:

r = np.dot(vector_a.reshape(1,3,1), vector_b.T.reshape(N, 1, 3))

and I was expecting r to be of shape (N,3,3) but I got a shape of (1,3,64,3)??? I don't know why I'm getting this shape. Both vector_a and vector_b are C contiguous. I tried to convert vector_b to F contiguous before doing the vector_b.T.reshape(N, 1, 3) but I still get the same r shape (1,3,64,3).

Does anybody know how to write the right expression?

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
martinako
  • 2,690
  • 1
  • 25
  • 44
  • 1
    What does `dot` say about arrays that are larger than 2d? – hpaulj Dec 07 '15 at 16:47
  • Thanks, I didn't read that. But I still can't get it to work... – martinako Dec 07 '15 at 16:54
  • This really isn't a `dot` case. The `einsum` expression does not sum anything. It can be done with plain multiplication (and broadcasting) `b.T[:,:,None] * a.T[None,:,:]`. – hpaulj Dec 07 '15 at 17:50

2 Answers2

4

As an alternative solution, if you use einsum, you can avoid having to reshape the array for the dot product:

np.einsum('ij,jk->kij', vector_a, vector_b)
Engineero
  • 12,340
  • 5
  • 53
  • 75
Alex Riley
  • 169,130
  • 45
  • 262
  • 238
  • I still need to fully understand einsum, but this works! thanks – martinako Dec 07 '15 at 16:58
  • 1
    No problem! `einsum` is incredibly useful - there are various answers explaining it [here](http://stackoverflow.com/questions/26089893/understanding-numpys-einsum) (including one I wrote ;-)). – Alex Riley Dec 07 '15 at 16:59
2

Here's one using broadcasting and ndarray.T -

vector_b.T[:,None,:]*vector_a
Divakar
  • 218,885
  • 19
  • 262
  • 358