필터 지우기
필터 지우기

2D Random walk angle

조회 수: 3 (최근 30일)
sweetdreams
sweetdreams 2015년 5월 6일
편집: Stephen23 2015년 5월 6일
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
sweetdreams
sweetdreams 2015년 5월 6일
oh wow...only 2 lines xD that's nice! thanks~

댓글을 달려면 로그인하십시오.

추가 답변 (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