I'm trying to make a graphic of a random walk in 1D, but i want that the first and the last point have a color (in this case the first one red and the last blue), but i dont know what i'm doing wrong..

This is my code:

RandomWalk[n_, d_] := 
NestList[(# + Table[Random[Real, {-1, 1}], {d}]) &, Table[0, {d}], 

OneDim = RandomWalk[5000, 1];

firstpoint = OneDim[[1]]

lastpoint = OneDim[[5001]]

ListPlot[{{Hue[0], PointSize[.02], 
Point[firstpoint]}, {Hue[.7], PointSize[.02], Point[lastpoint]}, 
  • $\begingroup$ my mistake, i want in 1D not in 2D, sorry $\endgroup$ Mar 22 '14 at 21:34
  • $\begingroup$ random walk in 1D? will be hard to see the path? $\endgroup$
    – Nasser
    Mar 22 '14 at 21:40
  • $\begingroup$ my teacher ask that, i know that i can have the graphic with: ListPlot[OneDim] but i would like to have the first and last point with a different color $\endgroup$ Mar 22 '14 at 21:43

There are several ways to do this. The structure of your 1d output is not optimal, because you get something like {{x1},{x2},...} which means a nested list. To make it short, if you want to use ListLinePlot, you can do it with the help of Epilog, which draws your first and last points on the final graphics:

oneDim = RandomWalk[500, 1];
 Epilog -> {PointSize[.04], Red, Point[{1, oneDim[[1, 1]]}], Blue, 
   Point[{Length[oneDim], oneDim[[-1, 1]]}]}]

Mathematica graphics

Another way is to use Graphics directly and just draw a line through all your points and mark the start and end points:

With[{data = MapIndexed[Join[#2/10, #1] &, oneDim]},
 Graphics[{Gray, PointSize[.02], Line[data], Red, Point[data[[1]]], 
   Blue, Point[Last[data]]}]

Mathematica graphics

Please note that I used MapIndexed to transform your 1d list into a list {{t1,x1},{t2,x2},...} where the t's are the increasing time.

  • $\begingroup$ thanks for help, but i just want with one coordinates because is 1D. Thanks anyway :) $\endgroup$ Mar 22 '14 at 21:53
  • 1
    $\begingroup$ @MarianadaCosta This is the way 1D random walks are visualized! Please read here: http://en.wikipedia.org/wiki/Random_walk $\endgroup$
    – halirutan
    Mar 22 '14 at 21:55
  • $\begingroup$ @halirutan That's why labeling axes is important :) $\endgroup$
    – Kuba
    Mar 22 '14 at 22:02

Ok, here it is 1D, not sure if I understood the question right, but see if this what you want

randomWalk[n_, d_] := Table[{RandomReal[{-1, 1}], 0}, {n}];
data = randomWalk[50, 1];

ListPlot[data, PlotStyle -> PointSize[.01], PlotRange -> {Automatic, {-.1, .1}}, 
  Epilog -> {PointSize[.02], Red, Point[data[[1]]], Blue, Point[data[[-1]]]}]

Mathematica graphics

  • $\begingroup$ exactly what i wanted, thanks :D $\endgroup$ Mar 22 '14 at 21:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.