Apr 25, 2013

Numpy broadcasting

When operands are not of the same dimension, NumPy expands the operands to be compatible with each other.

For example
In : x
Out: 
array([[0],
       [1],
       [2],
       [3]])

In : y
Out: array([ 1.,  1.,  1.,  1.,  1.])

In : x+y
Out: 
array([[ 1.,  1.,  1.,  1.,  1.],
       [ 2.,  2.,  2.,  2.,  2.],
       [ 3.,  3.,  3.,  3.,  3.],
       [ 4.,  4.,  4.,  4.,  4.]])

In : x.shape
Out: (4, 1)

In : y.shape
Out: (5,)

In : (x+y).shape
Out: (4, 5)
In the above example, as a consequence of broadcasting, the result is derived by repeating x 5 times and y 4 times and then adding them.

References:
http://www.scipy.org/EricsBroadcastingDoc
http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html