I'm doing a simple OLS regression and I strikes my attention that this very simple computation takes several seconds to perform in Mathematica

Sum[(x[[i]] - Mean[x]) (y[[i]] - Mean[y]), {i, 1, 40}]/ Sum[(x[[i]] - Mean[x])^2, {i, 1, 40}]

The equivalent in Maple is instantaneous:

(sum((x[i]-Mean(x))*(y[i]-Mean(y)), i = 1 .. 40))/(sum((x[i]-Mean(x))^2, i = 1 .. 40))

Am I doing something wrong?


1 Answer 1


Since Sum holds its arguments, it ends up computing Mean[x] and Mean[y] in every step in the sum. Try

Total[(x - Mean[x])(y - Mean[y])]/Total[(x - Mean[x])^2]

which uses vectorized operations. In general, Sum is most suited to compute sums of symbolic quantities, sums with symbolic limits etc. Total or Tr is much faster for numeric stuff.


Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.