1
$\begingroup$

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.

$\endgroup$
  • 1
    $\begingroup$ You might want to try expressing your functions in terms of actual dot products, for starters... $\endgroup$ – J. M. will be back soon Nov 2 '15 at 12:22
  • $\begingroup$ Can you be more specific? thanks $\endgroup$ – Ahmed Abo-Zaid Nov 2 '15 at 12:24
  • $\begingroup$ 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. $\endgroup$ – J. M. will be back soon Nov 2 '15 at 12:36
  • $\begingroup$ thanks I will try it and get back here afterwards $\endgroup$ – Ahmed Abo-Zaid Nov 2 '15 at 12:39
  • $\begingroup$ 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. $\endgroup$ – David G. Stork Nov 3 '15 at 0:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.