I am wondering if you have good ways to show plots inside a loop in mma. Usually, the output of Plot
function is not shown, for example in the following code:
For[i = 1, i <= 10, i++, Plot[Sin[i*x], {x, -Pi, Pi}]]
Thanks for your help.
Edit
In connection to my previous question, I already have the For loop, for example, like this For[i = 1, i <= 10, i++, Plot[Sin[i*x], {x, -Pi, Pi}]]
. Given this fact, I want to have something like "press any key to continue..." inside the For loop, then refresh the plot every time I press any random key. Could anybody give a complete working code?
The need to evaluate a function or expression repeatedly requires constructing a programming loop. There are several ways to do this in Mathematica; in this classnote, we learn the basics of programming loops.
In addition to being a powerful programming tool, Mathematica allows a wide array of plotting and graphing options.
Just use Print
:
For[i = 1, i <= 10, i++, Plot[Sin[i*x], {x, -Pi, Pi}] // Print]
or Monitor
:
Monitor[For[i = 1, i <= 10, i++, p = Plot[Sin[i*x], {x, -Pi, Pi}];
Pause[0.5]], p]
(Pause is used here to give some time to view the plot; the loop is pretty fast here. Remove if necessary)
EDIT
On request a version that is controlled by mouse clicks on the graph (key presses need the graph to have focus so you need to click anyway)
Monitor[For[i = 1, i <= 10, , p = Plot[Sin[i*x], {x, -Pi, Pi}]],
EventHandler[p, {"MouseDown" :> i++}]]
This is a pretty stupid way to do this. The loop redraws the plot continuously. So, a slightly (but still ugly) version might be:
s = True;
Monitor[
For[i = 1, i <= 10, ,
If[s,
(* Put main loop body here*)
p = Plot[Sin[i*x], {x, -Pi, Pi}]
(* end of main body *) ;
s = False (* prevents continuous re-evaluating main body *)
]
]
, EventHandler[p, {"MouseDown" :> (i++; s = True)}]
]
Just return a list of the plots, instead of using a For
loop:
Table[Plot[Sin[i*x], {x, -Pi, Pi}], {i, 1, 10}]
If you want them all concatenated as one plot, Show[listOfPlots]
is one way to do that:
Show[Table[Plot[Sin[i*x], {x, -Pi, Pi}], {i, 1, 10}]]
UPDATE
Here's one simple way using Dynamic
and EventHandler
:
DynamicModule[{i = 1},
EventHandler[Dynamic[Plot[Sin[i*x], {x, -Pi, Pi}]],
{"KeyDown" :> i++}
]
And here's a slightly more fancy interface made with Animate
:
Animate[Plot[Sin[i*x], {x, -Pi, Pi}], {i, 1, 10, 1}, AnimationRunning -> False]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With