![](https://secure.gravatar.com/avatar/764323a14e554c97ab74177e0bce51d4.jpg?s=120&d=mm&r=g)
On Tue, Mar 4, 2008 at 12:00 PM, John Reid <j.reid@mail.cryst.bbk.ac.uk> wrote:
This works fine:
In [49]: numpy.zeros((3,2))+numpy.array([1,2]) Out[49]: array([[ 1., 2.], [ 1., 2.], [ 1., 2.]])
but this doesn't: In [50]: numpy.zeros((3,2))+numpy.array([1,2,3]) --------------------------------------------------------------------------- ValueError Traceback (most recent call last)
C:\Dev\MyProjects\Bio\Python\site_dpm\<ipython console> in <module>()
ValueError: shape mismatch: objects cannot be broadcast to a single shape
<ipython console>(1)<module>()
what is the simplest way to get this addition to work?
Instead of adding a shape-(3,) array, make it a shape-(3,1) array. In [1]: from numpy import * In [2]: z = zeros((3,2)) In [3]: a = array([1,2,3]) In [5]: z + a[:,newaxis] Out[5]: array([[ 1., 1.], [ 2., 2.], [ 3., 3.]]) A good overview of broadcasting is here: http://www.scipy.org/EricsBroadcastingDoc -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco