Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Plotting results from for loop

  1. Apr 26, 2014 #1
    Plotting results from "for" loop


    I have a problem which it seems I couldn't solve. I have "for" loop which gives results of some calculations as, say, vectors with two coordinates. What I want is to plot the result as a point in the xy plane. This loop goes on and on with the calculations from the beginning to the end for some 1000 times. So I want to get the results, 1000 points, plotted on only one graph, not each point on its own graph. Ideally they could be joined by a line.

    How can I do this? I work in Mathematica.

    Last edited: Apr 26, 2014
  2. jcsd
  3. Apr 27, 2014 #2
    I don't know any Mathematica, but in any other program, you would NOT create any plots inside the loop...you simply collect the points and THEN right after the loop, you create the one plot of interest.

    Unless you are plotting real time data coming into the computer, etc., there is no need to even be updating a plot after every iteration of a loop...the loop will be done soon enough.
  4. Apr 28, 2014 #3
    Users coming from other programming languages usually pounce on For. In Mathematica there are usually other, often better, ways of doing this. Here is one way.

    Code (Text):
    ListPlot[Table[RandomReal[{-1, 1}, 2], {6}], Joined->True]
    Table is almost like For, it will repeat a calculation a certain number of times. The difference is that it will package up the results of all those calculations into a list and return it to you, so you can ListPlot the result for example.

    You can replace that RandomReal with other calculations. You can even do multiple steps if you carefully use a semicolon at the end of each of those and you make the last item be the result that you want to have stored in the list.

    Code (Text):
    But if you are compelled to use a For then you can use Sow and Reap to save up results.

    Code (Text):
    ListPlot[Reap[For[i=1, i<=6, i++, Sow[RandomReal[{-1,1}, 2]]]][[2,1]],Joined->True]
    In Mathematica there are always a dozen different ways of doing anything, at least several of which are completely incomprehensible. You could, for example, create an empty list and inside the For append the latest value to the end of the list AND then save that as the new value of the list. And there are other things you could do, but hopefully this is enough to get you started
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook