I am calculating a 3-by-3 matrix whose elements are given as follows:
$$ M_{mn} = \frac{1}{N}\sum_{i=1}^N \sum_{j=1}^N (r^i_m - r^j_m)(r^i_n - r^j_n) \tag{1} $$
where $N$ is the total number of particles, and $r^i_m$ denotes the m-th component of the i-th particle's vector. The sums can be computationally expensive as often $N$ is around $10000.$
Below is my implementation of the matrix $M$ in Mathematica:
matrixM = Table[(1./npart)*
Sum[Sum[(Part[vecs, i, m] - Part[vecs, j, m])*(Part[vecs, i, n] -
Part[vecs, j, n]), {j, 1, npart}], {i, 1, npart}], {m, 3}, {n, 3}];
and here vecs
is the array of all particle vectors (so one line per particle and each line of the array is a vector of 3 components).
- How could I speed up computations of this nature? Is there possibly a bottleneck in my efficiency due to the way I generate the matrix using
Table
or the fact that I access the components stored in a big array usingPart
? Any advice would be very helpful.
N
. It is a built-in functionality.. $\endgroup$npart
as variable name in my own notebook, here as I was writing the post I ended up using same names as in eq. (1), now it's replaced bynpart
instead ofN
in the shown code. $\endgroup$