Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show plots inside a loop in mathematica

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?

like image 313
Qiang Li Avatar asked Apr 06 '11 22:04

Qiang Li


People also ask

Can you use loops in Mathematica?

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.

Can you graph in Mathematica?

In addition to being a powerful programming tool, Mathematica allows a wide array of plotting and graphing options.


2 Answers

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)}]
 ]
like image 109
Sjoerd C. de Vries Avatar answered Sep 29 '22 20:09

Sjoerd C. de Vries


Just return a list of the plots, instead of using a For loop:

Table[Plot[Sin[i*x], {x, -Pi, Pi}], {i, 1, 10}]

enter image description here

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}]]

enter image description here

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]
like image 27
Michael Pilat Avatar answered Sep 29 '22 18:09

Michael Pilat