[SciPy-user] matrix multipy ...

Matteo Bertini matteo at naufraghi.net
Mon May 19 19:15:48 EDT 2008


Johann Cohen-Tanugi ha scritto:
> hi Matteo,
> 
> In [1]: import numpy as np
> 
> In [2]: aa = np.mat("1,2,3,4,5;6,7,8,9,0")
> 
> In [3]: bb = np.mat("1,2,3;4,5,6")
>
> In [5]: np.outer(aa,bb)
> Out[5]:
> array([[ 1,  2,  3,  4,  5,  6],
>        [ 2,  4,  6,  8, 10, 12],
>        [ 3,  6,  9, 12, 15, 18],
>        [ 4,  8, 12, 16, 20, 24],
>        [ 5, 10, 15, 20, 25, 30],
>        [ 6, 12, 18, 24, 30, 36],
>        [ 7, 14, 21, 28, 35, 42],
>        [ 8, 16, 24, 32, 40, 48],
>        [ 9, 18, 27, 36, 45, 54],
>        [ 0,  0,  0,  0,  0,  0]])
> 
> Is that what you were looking for?
> cheers,
> Johann

Not really, the loop I'd like to avoid is this:

In [63]: cc = N.zeros((bb.shape[0], aa.shape[1], bb.shape[1]))

In [64]: for i in range(cc.shape[0]):
   ....:     cc[i] = aa[i].T*bb[i]

In [66]: cc
Out[66]:
array([[[  1.,   2.,   3.],
        [  2.,   4.,   6.],
        [  3.,   6.,   9.],
        [  4.,   8.,  12.],
        [  5.,  10.,  15.]],

       [[ 24.,  30.,  36.],
        [ 28.,  35.,  42.],
        [ 32.,  40.,  48.],
        [ 36.,  45.,  54.],
        [  0.,   0.,   0.]]])

The outer product produces the same results in Q1 and Q3, but does
useles (in this case :P) computation in Q2 and Q4.

Dunno if the computation can be faster, but I'd like to find out if
there is a slice trick to do this kind of things.

Thank you,
Matteo




More information about the SciPy-User mailing list