Random Walk Problem (Plots)

I have the following question in hand:
Create a random walk of length 40, 000 in the plane starting at the origin with unit step size and uniformly distributed angles between 0 and 2π. Plot the walk, and colour red the endpoints of each step that is between 100 and 200 units from the origin.
This is my code for creating the random walk in 2D :
numberOfSteps = 40000; % Totlal number of steps
x(1) = 0.0; % Initial position (x)
y(1) = 0.0; % Initial position (y)
for i = 1:numberOfSteps % (Looping from 1 to 40000)
theta = 2*pi*rand(); % Arbritary angle in between 0 and 2Pi
r = 1; % Distance Travelled
dx = r*cos(theta); % Step Size (x)
dy = r*sin(theta); % Step Size (y)
x(i+1) = x(i) + dx; % Position at the end of the first step (x)
y(i+1) = y(i) + dy; % Position at the end of the second step (y)
end
plot(x,y,'r');
This all works to create a random walk .. but how would I color each step that is between the given interval (100,200) ?

 采纳的回答

numberOfSteps = 40000; % Totlal number of steps
x(1) = 0.0; % Initial position (x)
y(1) = 0.0; % Initial position (y)
for i = 1:numberOfSteps % (Looping from 1 to 40000)
theta = 2*pi*rand(); % Arbritary angle in between 0 and 2Pi
r = 1; % Distance Travelled
dx = r*cos(theta); % Step Size (x)
dy = r*sin(theta); % Step Size (y)
x(i+1) = x(i) + dx; % Position at the end of the first step (x)
y(i+1) = y(i) + dy; % Position at the end of the second step (y)
end
plot(x,y,'k');
hold on
dist = sqrt(x.^2 + y.^2);
mask = 100 < dist & dist < 200;
scatter(x(mask), y(mask), 'r.');
hold off

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Delaunay Triangulation 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by