Simulating a 2D Random Walk
Show older comments

How can I turn a 1d random walk into a 2d random walk???
This is my code for 1d random walk:
N = 100; % Number of steps
single_trajectory = simulateRandomWalk(N);
figure
plot(0:N, single_trajectory, '-o')
title('1D Random Walk - Single Trajectory')
xlabel('Steps')
ylabel('Position')
P_values = [50, 500, 5000, 50000, 500000];
for p_index = 1:length(P_values)
P = P_values(p_index);
final_positions = zeros(1, P);
for i = 1:P
single_trajectory = simulateRandomWalk(N);
final_positions(i) = single_trajectory(end);
end
% Plot histogram of final positions
figure
histogram(final_positions, 'Normalization', 'probability')
title(['Histogram for P = ' num2str(P)])
xlabel('Final Position')
ylabel('Probability')
end
function trajectory = simulateRandomWalk(N)
% Initialize position
position = 0;
% Initialize trajectory array
trajectory = zeros(1, N+1);
trajectory(1) = position;
% Simulate random walk
for step = 1:N
% Generate a random number to decide left or right movement
move = randi([0, 1])*2 - 1; % -1 for left, 1 for right
% Update position
position = position + move;
% Store the current position in the trajectory array
trajectory(step+1) = position;
end
end
Answers (2)
Walter Roberson
on 6 Dec 2023
Call simulateRandomWalk twice, once to get an x trajectory and once to get a y trajectory. Then put them together,
plot(first_trajectory, second_trajectory)
2 Comments
William
on 11 Dec 2023
N = 100; % Number of steps
x_trajectory = simulateRandomWalk(N);
y_trajectory = simulateRandomWalk(N);
figure
plot(x_trajectory, y_trajectory, '-o')
title('1D Random Walk - Single Trajectory')
xlabel('Steps')
ylabel('Position')
function trajectory = simulateRandomWalk(N)
% Initialize position
position = 0;
% Initialize trajectory array
trajectory = zeros(1, N+1);
trajectory(1) = position;
% Simulate random walk
for step = 1:N
% Generate a random number to decide left or right movement
move = randi([0, 1])*2 - 1; % -1 for left, 1 for right
% Update position
position = position + move;
% Store the current position in the trajectory array
trajectory(step+1) = position;
end
end
Image Analyst
on 11 Dec 2023
0 votes
See attached demos for random walks. I think all of them are 2-D.
Categories
Find more on Triangular Distribution 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!