2D Random walk angle
1 回表示 (過去 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...
0 件のコメント
採用された回答
Walter Roberson
2015 年 5 月 6 日
[deltax, deltay] = pol2cart(2*Pi*rand(1,n), 1);
plot(cumsum(deltax), cumsum(deltay))
その他の回答 (1 件)
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:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/176614/image.jpeg)
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!
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!