# Plotting results from for loop

Tags:
1. Apr 26, 2014

### nikolafmf

Plotting results from "for" loop

Hello,

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.

Sincerely,
Nikola

Last edited: Apr 26, 2014
2. Apr 27, 2014

### gsal

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.

3. Apr 28, 2014

### Bill Simpson

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):
ListPlot[Table[x=RandomReal[{-1,1}];y=RandomReal[{-2,2}];x=2*x-y;{x,y},{6}],Joined->True]
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