The question is simple. I'm trying to improve the (time) performance of a "Do" loop that looks like the following MWE
xlist = Range[0., 1., 0.1]; ylist = Range[0., 2., 0.2]; f[x_, y_, z_] := x + 3*y - z results = {}; Do[ input = Tuples[{xlist, ylist, {step}}]; evalf = f @@ Transpose[input]; AppendTo[results, {step, Mean@evalf}] , {step, Range[-1., 1., 0.1]}]
What is the most efficient way to speed up a thing like this?
Table
instead of aDo
andAppendTo
here. Also an iterator of the form{step, -1, 1, 0.1}
might be better, instead of computing the wholeRange
; not sure.$\endgroup$Tuples
each time, since thestep
is constant in a given, well, step! Maybe simply computexylist = Transpose @ Tuples[{xlist, ylist}]
outside the loop, then instead ofDo
useresults = Table[{step, Mean[f[#1, #2, step]& @@ xylist]}, {step, -1, 1, 0.1}]
. Does that work as expected? (Sorry, not at a computer rn...)$\endgroup$Mean[#1 + 3*#2 & @@ Transpose[Tuples[{xlist, ylist}]
, or analytically simply $\bar{x} + 3\bar{y} = 0.5 + 3$, and thenresults = Table[{step, 3.5 - step}, {step, -1, 1, 0.1}]
, I think, but assuming you want to use an arbitrary function in general... :P$\endgroup$With[{ran = Range[-1., 1., 0.1]}, Transpose[{ran, Mean[xlist] + 3 Mean[ylist] - ran}] ]
$\endgroup$