1

After some symbolic calculations I have an expression with 5 symbolic variables: expr = f(v1, v2, v3, v4, v5). Each variable is a range of values, e.g.:

v1 = Range[1, 15, 1]
v2 = Range[0.5, 3, 0.1]
... 

I would like to evaluate the expression for each combination of all values in all variables and take mean and standard deviation from it.

I tried

exprEval = Table[Table[Table[Table[Table[expr, {v1, 1, 15, 1}], {v2, 0.5, 3, 0.1}], {v3,...}], {v4, ...}], {v5, ...}]
exprEvalMean = Mean[Flatten[exprEval]]

But this either takes forever or crashes with memory error. Is there another, more efficient way to do this?

user_185051
  • 426
  • 5
  • 19
  • 1
    This doesn't affect the performance much, but you can replace the nested `Table`s by one: `Table[ expr, {v1,..}, {v2,..} , {v3,..}]`. – And R Apr 01 '16 at 09:27

2 Answers2

1

With three sets of variable values

v1 = Range[1, 3, 1];
v2 = Range[1.1, 1.5, 0.2];
v3 = Range[300, 400, 100];

Say your expression is the product of the variables

f[a_, b_, c_] := a b c

Then

res = f[Sequence @@ #] & /@ Tuples[{v1, v2, v3}];
Through@{Mean, StandardDeviation}[res]
(* {910., 428.348} *)

Hope this helps.

Edmund
  • 488
  • 4
  • 21
0
v1 = Range[1, 3, 1];
v2 = Range[1.1, 1.5, 0.2];
v3 = Range[300, 400, 100];

Print[out = Outer[List, v1, v2, v3]];

Print[avg = Mean[Flatten[out]]];
Print[sd = StandardDeviation[Flatten[out]]];
Chris Degnen
  • 8,443
  • 2
  • 23
  • 40
  • You can avoid all the `Print`s by placing those commands in a new cell of the notebook. – Edmund Mar 30 '16 at 16:32
  • @Edmund I was making it easier for copy & paste into Mathematica. Without semicolons the lines join together when pasted. – Chris Degnen Mar 30 '16 at 17:39