2D Random walk angle

3 次查看(过去 30 天)
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...

采纳的回答

Walter Roberson
Walter Roberson 2015-5-6
[deltax, deltay] = pol2cart(2*Pi*rand(1,n), 1);
plot(cumsum(deltax), cumsum(deltay))

更多回答(1 个)

Stephen23
Stephen23 2015-5-6
编辑:Stephen23 2015-5-6
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!

类别

Help CenterFile Exchange 中查找有关 2-D and 3-D Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by