# Speed matrix multiplications

I am trying to run this function

Pfun[M_, G_] :=
Module[{resfn, P, resmatrix},

P[u_, v_] := Sum[M[[i,u]]*M[[j,v]]*A[[i,j]], {i, n}, {j, n}]/
(Total[M[[All,u]]]*Total[M[[All,v]]]);

resfn[i_, u_] :=
Product[
(If[P[u, v] < 10^(-3),
(10^(-3))^Sum[M[[j,v]]*A[[i,j]], {j, Complement[Range[n], {i}]}],
P[u, v]^Sum[M[[j,v]]*A[[i,j]], {j, Complement[Range[n], {i}]}]])
(If[1 - P[u, v] < 10^(-3),
(10^(-3))^Sum[M[[j,v]]*(1 - A[[i,j]]),
{j, Complement[Range[n], {i}]}], (1 - P[u, v])^
Sum[M[[j,v]]*(1 - A[[i,j]]), {j, Complement[Range[n], {i}]}]]),
{v, k}];

resmatrix = Table[resfn[i, u], {i, n}, {u, k}]];


but it takes so much time. How can I increase the speed of this function?

Here M and A are 0-1 matrices, and G is real matrix. I am trying for n = 1162 and k = 3.

• You might want to try expressing your functions in terms of actual dot products, for starters... – J. M. will be back soon Nov 2 '15 at 12:22
• Can you be more specific? thanks – Ahmed Abo-Zaid Nov 2 '15 at 12:24
• Something for you to start with: P[u_, v_] := M[[All, u]].A.M[[All, v]]/(Total[M[[All, u]]] Total[M[[All, v]]]). Once more: look into using dot products. – J. M. will be back soon Nov 2 '15 at 12:36
• thanks I will try it and get back here afterwards – Ahmed Abo-Zaid Nov 2 '15 at 12:39
• Avoid using upper-case letters (A, P, M, G, etc.) or words that begin with upper-case letters (Pfun, etc.) as these may conflict with internal names in Mathematica. – David G. Stork Nov 3 '15 at 0:51