[SciPy-user] Newbie broadcasting question
John Reid
j.reid at mail.cryst.bbk.ac.uk
Tue Mar 4 13:00:43 EST 2008
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? I would like the
following
array([[ 0., 0.],
[ 0., 0.],
[ 0., 0.]])
+
array([1,2,3])
=
array([[ 1., 1.],
[ 2., 2.],
[ 3., 3.]])
In general my arrays are held in variables and are not constructed on
the fly so while this works
numpy.zeros((3,2)).T+numpy.array([1,2,3])
which works fine with the '+' operator but not with '+='. This doesn't work:
In [54]: a=zeros((3,2))
In [55]: a.T += numpy.array([1,2,3])
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
C:\Dev\MyProjects\Bio\Python\site_dpm\<ipython console> in <module>()
AttributeError: attribute 'T' of 'numpy.ndarray' objects is not writable
> <ipython console>(1)<module>()
My guess is that I should do
a = (a.T + numpy.array([1,2,3])).T
but I wonder if there is a more efficient way. Am I missing something?
Thanks,
John.
More information about the SciPy-User
mailing list