Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elementwise multiplication of arrays of different shapes in python

Say I have two arrays a and b,

  a.shape = (5,2,3)
  b.shape = (2,3)

then c = a * b will give me an array c of shape (5,2,3) with c[i,j,k] = a[i,j,k]*b[j,k].

Now the situation is,

  a.shape = (5,2,3)
  b.shape = (2,3,8)

and I want c to have a shape (5,2,3,8) with c[i,j,k,l] = a[i,j,k]*b[j,k,l].

How to do this efficiently? My a and b are actually quite large.

like image 543
user1342516 Avatar asked May 20 '12 21:05

user1342516


1 Answers

This should work:

a[..., numpy.newaxis] * b[numpy.newaxis, ...]

Usage:

In : a = numpy.random.randn(5,2,3)

In : b = numpy.random.randn(2,3,8)

In : c = a[..., numpy.newaxis]*b[numpy.newaxis, ...]

In : c.shape
Out: (5, 2, 3, 8)

Ref: Array Broadcasting in numpy

Edit: Updated reference URL

like image 118
Avaris Avatar answered Oct 30 '22 10:10

Avaris