1
m = {{1, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 
1}, {1, 1}, {1, 1}};
m2 = {{1, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 
1}, {1, 1}, {1, 1}};
Manipulate[
 Do[
  m[[n]] = m[[n]] + RandomChoice[{{0, 1}, {1, 0}, {0, -1}, {-1, 0}, {0, 0}}];
  , {n, 10}];
 Do[
 m2[[n]] = m2[[n]] + RandomChoice[{{0, 1}, {1, 0}, {0, -1}, {-1, 0}, {0, 0}}];
   , {n, 10}];
Show[ListPlot[m, PlotStyle -> Red]
  , ListPlot[m2, PlotStyle -> {PointSize[0.03]}]]
, {n, 1, 20}]

This is pseudo-randomwalk. I want to plot in only square (0,0),(100,0),(0,100),(100,100). Please teach me the random walk in limited range.

Shakariky
  • 31
  • 4

1 Answers1

1

This modification of m_goldberg's code should work on version 9.0

nextPt[pt_, r_, bounds_] := 
  Block[{nxt = pt + r {Cos[#], Sin[#]} &[RandomReal[2. π]]}, 
   If[And @@ Thread[bounds[[1]] <= nxt <= bounds[[2]]], Return[nxt]];
   nextPt[pt, r, bounds]];
walk[start : {_Real, _Real}, range : {_Real, _Real}, r_Real?Positive, 
   steps_Integer?Positive] := 
  Module[{bounds}, bounds = {start - range/2, start + range/2};
   NestList[nextPt[#, r, bounds] &, start, steps]];
walkAnimation[path_, opts : OptionsPattern[]] :=
  ListAnimate[
   Table[
    Graphics[{Line[path[[;; n]]],
      Red, Disk[First[path], Scaled[.015]],
      Blue, Disk[path[[n]], Scaled[.015]]},
     opts, Frame -> True],
    {n, Length@path}], 10];

walkAnimation[walk[{50., 50.}, {100., 100.}, 5., 200], 
 PlotRange -> {{0, 100}, {0, 100}}]

enter image description here

Jason B.
  • 68,381
  • 3
  • 139
  • 286
  • Glad to help, welcome to the site, take the [tour], come back if you have other troubles, and try to answer questions when you can. Next time you have a question, if you are still using a previous version of Mathematica, be sure to include that in the quesiton, as it can help get to the pertinent info more quickly. – Jason B. Apr 04 '16 at 09:35