开发者

How to show plots inside a loop in mathematica

开发者 https://www.devze.com 2023-02-23 03:18 出处:网络
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:

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 fac开发者_C百科t, 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?


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

How to show plots inside a loop in mathematica

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

How to show plots inside a loop in mathematica

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 really want to have the user press a key between Plots, the simplest way might be

For[i = 1, i <= 10, i++, 
    If[!ChoiceDialog[Plot[Sin[i*x], {x, -Pi, Pi}], 
         WindowTitle -> "Plot #" <> ToString[i] 
                                 <> ":  Press OK or Enter to continue"],
    Abort[]]]

How to show plots inside a loop in mathematica

0

精彩评论

暂无评论...
验证码 换一张
取 消