2D random walk double for loop
Show older comments
Question: Consider a particle which starts from the origin, and it moves in a random direction in each timestep: (∆x,∆y) = (dcosθ,dsinθ) where d = 0.01 and θ is a random number between 0 and 2π. Plot the positions of Np = 2000 independent random particles at timestep 2000 in the x-y plane.
I have managed to plot the path of 1 particle walking for 2000 steps (it was the previous part of this question) but I don't seem to be able to create a double for loop correctly to plot the final position of 2000 particles. The program just keeps running and nothing happens.
Where did I make a mistake?
clear % clear variables and functions from memory
d=0.01 % initial condition
for j=1:2000 % Repeat for 2000 particles
for i=1:2000 % Time-evolution of a single particle
theta = 2*pi*rand(2000,1); % theta= random angle between 0 and 2pi
% for 2000 steps
x(1)=0 % initial condition x=0
y(1)=0 % initial condition y=0
x(i+1) = x(i)+d*cos(theta(i,1)); % define i-th element of x vector
y(i+1) = y(i)+d*sin(theta(i,1)); % define i-th element of y vector
end
xfinal(j)=x(2001); % the position of the j-th particle
yfinal(j)=y(2001);
rfinal(j)=sqrt(x(2001)^2+y(2001)^2); % the distance from the origin
end
plot(xfinal,yfinal,"bo") % plots final position
axis equal % sets the aspect ratio so that equal tick mark
% increments on the x and y axis are equal in size.
xlabel('X','FontSize',20) % X-axis label
ylabel('y','FontSize',20) % Y-axis label
grid on % adds grid
grid minor % adds finer grid
Accepted Answer
More Answers (0)
Categories
Find more on Numerical Integration and Differentiation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!