[SciPy-user] Mathematica Element-wise Multiplication

Johann Cohen-Tanugi cohen at slac.stanford.edu
Sun Dec 16 19:28:14 EST 2007


Actually I do not manage to use .T or .transpose() method on 1D arrays :

In [42]: a = array([[ 0.0, 0.0, 
0.0],[10.0,10.0,10.0],[20.0,20.0,20.0],[30.0,30.0,30.0]])   <--this is 
example 3 of thiis indeed very nice tutorial on broadcasting
In [43]: b = array([1.0,2.0,3.0,4.0])
In [44]: a+b
ValueError: shape mismatch: objects cannot be broadcast to a single 
shape    <----- fine, mismatch of trailing dimensions

In [45]: b.transpose()
Out[45]: array([ 1.,  2.,  3.,  4.])     <------ ominous : no change

In [47]: a+b.transpose()
ValueError: shape mismatch: objects cannot be broadcast to a single 
shape    <-----transpose did not work

In [48]: a+b.T
ValueError: shape mismatch: objects cannot be broadcast to a single 
shape    <------ nor .T

In [49]: b = array([[1.0],[2.0],[3.0],[4.0]])
In [51]: a+b
Out[51]:
array([[  1.,   1.,   1.],
       [ 12.,  12.,  12.],
       [ 23.,  23.,  23.],
       [ 34.,  34.,  34.]])     <------------ expected result for the 
brodcast of b as a column vector into a

In [52]: aa=array([[1,2],[3,4]])

In [53]: aa.transpose()
Out[53]:
array([[1, 3],
       [2, 4]])
                                      <------------- transpose and T 
work for this 2D array
In [55]: aa.T
Out[55]:
array([[1, 3],
       [2, 4]])


So, what is going on? Is that a bug, a feature, or some weir failure of 
my install?

thanks,
Johann

Stefan van der Walt wrote:
> Hi Tom
>
> On Fri, Dec 14, 2007 at 09:26:59PM -0800, Tom Johnson wrote:
>   
>> While playing with Mathematica, I must say that I was surprised to
>> find that it handled element-wise multiplication differently from
>> scipy.
>>
>> In scipy,
>>
>>     
>>>>> A = array([[1,2],[3,4]])
>>>>> B = array([2,3])
>>>>> A * B
>>>>>           
>> array([[2,6],[6,12]])
>>
>> which essentially multiplies each COLUMN of A with each COLUMN of B.
>>     
>
> Numpy does what we call broadcasting.  You can read more about it at
>
> http://www.scipy.org/EricsBroadcastingDoc
>
> If you'd like to have the Mathematica behaviour, you can always use
> the transpose property (i.e. x.T).
>
> Regards
> Stéfan
> _______________________________________________
> SciPy-user mailing list
> SciPy-user at scipy.org
> http://projects.scipy.org/mailman/listinfo/scipy-user
>   




More information about the SciPy-User mailing list