MathGroup Archive 2004

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Matrix Dot Product

  • To: mathgroup at smc.vnet.net
  • Subject: [mg52193] Re: Matrix Dot Product
  • From: Peter Pein <petsie at arcor.de>
  • Date: Sun, 14 Nov 2004 04:30:51 -0500 (EST)
  • References: <cn4lbm$13s$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

MacDonald, Calum (MAT) wrote:
> Hi
> 
> I was wondering if someone could please help me with a command for
> calculating the dot product of two (NxN) matrices. 
> 
> For example, for  two (2x2) matrices, A and B, we define the dot product
> as:
> 
> A(1,1)*B(1,1) + A(2,1)*B(2,1) + A(1,2)*B(1,2) + A(2,2)*B(2,2)
> 
> i.e. we multiply corresponding entries of the matrices and sum these
> values.
> 
> It is easy to write this in a loop but for large matrices the
> calculation is rather slow.
> 
> Is there a Mathematica function that I can call that will allow me to do
> this faster?
> 
> Thanks
> 
> Calum
> 
> 
> 
In[1]:=
   matrixDot[a_, b_] := Dot @@@ Transpose[{a, b}] // Tr
In[2]:=
   m1 = Table[a[i, j], {i, 5}, {j, 3}];
   m2 = Table[b[i, j], {i, 5}, {j, 3}];
In[4]:=
   matrixDot[m1, m2]
Out[4]=
   a[1, 1] b[1, 1] + a[1, 2] b[1, 2] + a[1, 3] b[1, 3] +
   a[2, 1] b[2, 1] + a[2, 2] b[2, 2] + a[2, 3] b[2, 3] +
   a[3, 1] b[3, 1] + a[3, 2] b[3, 2] + a[3, 3] b[3, 3] +
   a[4, 1] b[4, 1] + a[4, 2] b[4, 2] + a[4, 3] b[4, 3] +
   a[5, 1] b[5, 1] + a[5, 2] b[5, 2] + a[5, 3] b[5, 3]
In[5]:=
   m1 = Partition[Table[Random[], {10^6}], 10^3];
   m2 = Partition[Table[Random[], {10^6}], 10^3];
   Timing[matrixDot[m1, m2]]
Out[7]=
   {0.821 Second, 249923.}

with Mathematica 4.0 on a PII/300 Win2k

-- 
Peter Pein
Berlin


  • Prev by Date: Re: Poles and Complex Factoring
  • Next by Date: Re: Matrix Dot Product
  • Previous by thread: Re: Matrix Dot Product
  • Next by thread: Re: Matrix Dot Product