2D random walk double for loop
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
Agnish Dutta
2019-4-11
I used the following method to generate the x and y coordinates od 2000 points moving randomly in 2D cartesian space. I was then able to use the "plot" function to track their movement.
pos_x = zeros(1, 2000);
pos_y = zeros(1, 2000);
d = 0.01;
for i = 1:2000
theta = 2*pi*rand(1, 2000);
pos_x(end + 1, :) = pos_x(end) + d.*cos(theta);
pos_y(end + 1, :) = pos_y(end) + d.*sin(theta);
end
% pos_x(i, j) = X-cooridnate of the jth particle at instance 'i'.
% pos_y(i, j) = Y-cooridnate of the jth particle at instance 'i'.
The next thing would be to plot the particle's movements in the cartesian plane.
for i = 1:2000
plot(pos_x(:, i), pos_y(:, i));
hold on;
end
Plotting all the 2000 points on the same figure can get messy though. I suggest plotting 3-5 of them at a time.
Here is some additional material I found related to visualizing random walks:
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Two y-axis 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!