My problem is a classic one: I want to plot a function-generated list, and there's no way to pre-evaluate (because the actual function includes NMinimize
and thus cannot be calculated on symbolic values). I use the following replacement for the actual function:
f[x_?NumericQ]:={x,x^2}
Now doing
Plot[f[x], {x, 0, 1}, Evaluated->True]
will still generate only one colour, as evaluation with a symbolic value will not generate a list. So I thought I could bypass this by just saving the result in a temporary variable and creating a wrapper function to read that out again (after all, unlike Mathematica, I do know the shape of the generated list):
Module[{fwrap1,fwrap2,tmp},
fwrap1[x_?NumericQ] := (tmp = f[x])[[1]];
fwrap2[x_?NumericQ] := tmp[[2]];
Plot[{fwrap1[x], fwrap2[x]}, {x, 0, 1}]]
I expected this to work as follows:
- First,
fwrap1
is called, which obtains the complete list fromf
, stores it intmp
and returns the first item. - Then,
fwrap2
is called, which just reads the second value whichfwrap1
stored intmp
.
However while this indeed gives two colours as expected, the second function is replaced with a constant value (the one at maximal x).
By having fwrap2
increment a counter, I can verify that it is called 53 times, and by recording the minimal and maximal x, I can verify that it is indeed called on the complete interval (well, at least at both end points). Moreover, adding lines of the form
Print[{fwrap1[0.5],fwrap2[0.5]}];
inside the module (with different values each time) gives the expected output.
So why does this code not work?
x
,fwrap1
is called, thenfwrap2
. However, from the behavior you observe I suspect thatPlot
calculates all values forfwrap1
first, repeatedly rewriting the value oftmp
and discarding the intermediate values you wanted to save; only afterwards does it move on tofwrap2
. This would seem to make sense with the fact that only the value oftmp
corresponding to one of the boundaries of the $x$ range is retained. $\endgroup$ – MarcoB Oct 20 '15 at 17:33fwrap1
, and then another row of calls only tofwrap2
. If you turn your comment into an answer, I'll accept it. $\endgroup$ – celtschk Oct 20 '15 at 17:55