I found that Mathematica's Expectation operator is slow for Gaussian random variables, I'd like to scale to 100 dimensions, but it currently takes 10 seconds for 10 dimensions, looking forward to tips on how to speed this up.
Problem: for a Gaussian random variable $x$ in $d$ dimensions, compute the following quantities $$E[xx'],E[xx'xx'],E[xx'\otimes xx']$$
$\otimes$ refers to KroneckerProduct
CircleTimes = KroneckerProduct;
problemSetup[d_] := (
cov = DiagonalMatrix@Table[1/k, {k, 1, d}];
dist = MultinormalDistribution[N@cov];
Clear[x];
xvec = Array[x, d];
X2 = Expectation[xvec\[CircleTimes]xvec,
xvec \[Distributed] dist];
X2X2 =
Expectation[(xvec\[CircleTimes]xvec).(xvec\[CircleTimes]xvec),
xvec \[Distributed] dist];
X4 = Expectation[Outer[Times, xvec, xvec, xvec, xvec],
xvec \[Distributed] dist];
X4flat = Flatten[X4, {{1, 2}, {3, 4}}];
);
problemSetup[10] // Timing (* {10.3734, Null} *)
```
Outer[Times, xvec, xvec, xvec, xvec]
probably takes 2 minutes withd=100
. I suspect that @ciao is using the following:AbsoluteTiming[Outer[Times, xvec, xvec, xvec, xvec] /. {x[k_]^4 -> 3/k^2, x[k_]^3 -> 0, x[k_]^2 -> 1/k, x[k_] -> 0};]
. $\endgroup$