Random Walk Simulation for Multiple Particles

8 views (last 30 days)
Im trying to perform a randown walk for 1000 particles, simuating each for 20 steps. Im then supposed to calcualte and plot the mean square displacement but im not sure how. Here's what i have so far...
% Simulation of a random walk (delta = 1, tau = 1)
rng('Shuffle')
nSteps = 20;
positionArray = zeros(nSteps+1, 1);
stepNumber = 0:nSteps;
position = 0;
for index = 1:nSteps
randomMove = rand; % random number between 0 and 1; used to decide direction of random move
if (randomMove <= 0.5)
position = position+1; % move right
else
position = position-1; % move left
end
positionArray(index+1) = position; % store position
end
plot(stepNumber,positionArray,'k') % plot the position as a function of step number
set(gca,'FontSize',10);
xlabel('number of steps','FontSize',10)
ylabel('position','FontSize',10)

Answers (1)

Alan Stevens
Alan Stevens on 4 Feb 2021
Do you mean like this:
% Simulation of a random walk (delta = 1, tau = 1)
rng('Shuffle')
trials = 1000;
nSteps = 20;
positionArray = zeros(nSteps+1, 1);
stepNumber = 0:nSteps;
meansquaredisplacement = zeros(trials,1);
for trial = 1:trials
squareposn = 0;
position = 0;
for index = 1:nSteps
randomMove = rand; % random number between 0 and 1; used to decide direction of random move
if (randomMove <= 0.5)
position = position+1; % move right
else
position = position-1; % move left
end
end
squareposn = squareposn + position^2;
meansquaredisplacement(trial) = squareposn/nSteps;
end
plot(1:trials,meansquaredisplacement,'k') % plot the msd as a function of step number
set(gca,'FontSize',10);
xlabel('trial','FontSize',10)
ylabel('mean square displacement','FontSize',10)

Categories

Find more on General Physics 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!