[Numpy-discussion] Combination of element-wise and matrix multiplication

lorenzo bolla lbolla@gmail....
Fri Jul 4 02:38:19 CDT 2008


If a and b are 2d arrays, you can use numpy.dot:

In [36]: a
Out[36]:
array([[1, 2],
       [3, 4]])
In [37]: b
Out[37]:
array([[5, 6],
       [7, 8]])
In [38]: numpy.dot(a,b)
Out[38]:
array([[19, 22],
       [43, 50]])

If a and b are 3d arrays of shape 2x2xN, you can use something like that:
In [52]: a = numpy.arange(16).reshape(2,2,4)
In [53]: b = numpy.arange(16,32).reshape(2,2,4)
In [54]: c = numpy.array([numpy.dot(a[...,i],b[...,i]) for i in
xrange(a.shape[-1])])
In [55]: c.shape
Out[55]: (4, 2, 2)

Here c has shape (4,2,2) instead (2,2,4), but you got the idea!

hth,
L.


On Thu, Jul 3, 2008 at 9:53 PM, Jonno <jonnojohnson@gmail.com> wrote:

> I have two 2d arrays a & b for example:
> a=array([c,d],[e,f])
> b=array([g,h],[i,j])
> Each of the elements of a & b are actually 1d arrays of length N so I
> guess technically a & b have shape (2,2,N).
> However I want to matrix multiply a & b to create a 2d array x, where
> the elements of x are created with element-wise math as so:
> x[0,0] = c*g+d*i
> x[0,1] = c*h+d*j
> x[1,0] = e*g+f*i
> x[1,1] = e*h+f*j
>
> What is the simplest way to do this? I ended up doing the matrix
> multiplication of a & b manually as above but this doesn't scale very
> nicely if a & b become larger in size.
>
> Cheers,
>
> Jonno.
>
> --
> "If a theory can't produce hypotheses, can't be tested, can't be
> disproven, and can't make predictions, then it's not a theory and
> certainly not science." by spisska  on Slashdot, Monday April 21, 2008
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion@scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion
>



-- 
"Whereof one cannot speak, thereof one must be silent." -- Ludwig
Wittgenstein
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/numpy-discussion/attachments/20080704/06b5be6d/attachment.html 


More information about the Numpy-discussion mailing list