I want to make a function to simulate a 2D random walk.
Each step will have length 1 at a random angle (between 0 and 2pi for each step).
So the function will take input n = number of steps and return the distance covered d
But I'm having trouble with the angle part...

 Respuesta aceptada

Walter Roberson
Walter Roberson el 6 de Mayo de 2015

0 votos

[deltax, deltay] = pol2cart(2*Pi*rand(1,n), 1);
plot(cumsum(deltax), cumsum(deltay))

1 comentario

sweetdreams
sweetdreams el 6 de Mayo de 2015
oh wow...only 2 lines xD that's nice! thanks~

Iniciar sesión para comentar.

Más respuestas (1)

Stephen23
Stephen23 el 6 de Mayo de 2015
Editada: Stephen23 el 6 de Mayo de 2015

1 voto

Rather than doing this in a loop, which will be very slow and inefficient use of MATLAB, this can easily be written as vectorized code, which will be much faster, neater, and less buggy than doing this in a loop.
For example this is the complete code needed to generate and plot some random walks with a constant step-size and a random direction:
mxS = 20;
wlk = 10;
ang = 2*pi*rand(mxS,wlk);
poX = cumsum([zeros(1,wlk);cos(ang)]);
poY = cumsum([zeros(1,wlk);sin(ang)]);
plot(poX,poY,'x-')
axis equal
Where each column of poX and poY are the x and y positions for one walk. The plot look like this:
I used a step-size of one and the walks all start at the origin: doing this makes detecting the bounding box-intersection much easier as the bounding box can then be a simple positive value allowing a basic logical conditional to detect that the path is still inside the bounding box:
>> box = 5;
>> idx = abs(poX)<box & abs(poY)<box;
>> idx(~cumprod(+idx,1)) = false;
where the values of idx indicate whether the step is inside the box, and again each column corresponds to one walk. We can then use any to check which walks reached the bounding box:
>> any(~idx,1)
ans =
1 1 0 0 0 0 1 1 0 1
This tell shows clearly that five of these ten random trials trials reached the box. You can count how many steps were required by summing these indices:
>> sum(idx,1)
ans =
12 11 21 21 21 21 15 20 21 18
The shortest path to the boundary was only eleven steps. Note how the values correspond to the logical values above.
No loops: Faster, Neater, Easier!

Categorías

Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 6 de Mayo de 2015

Editada:

el 6 de Mayo de 2015

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by