How to generate a 1D random walk of 100 sample paths, along with sample mean and variance?

15 views (last 30 days)
So I need to generate a figure that represents 100 random walks (1D) and the mean, square root of variance with it. It should look like the example above, with much more lines to represent the walks. How can I code this problem?
I've tried the following, but it only produced the mean and variance. I'm not very good at MATLAB, so any kind of specific help would be welcome!
close all;
n = 100; % number of steps
nwalk = 10000; % number of walks
X = zeros(nwalk,n);
X2avg = zeros(n);
% r = rand();
for j = 1:nwalk
X(j,1) = 0; % initial position
r = rand(); % getting random number to decide step left or step right
for i = 2:n
if r < 0.5
X(j,i) = X(j,i-1)+1; % step to the right
elseif r > 0.5
X(j,i) = X(j,i-1)-1; % step to the left
X2avg(i) = X2avg(i) + X(j,i)^.2; % accumulating squared displacement
for i = 2:n % normalizing the squared displacement
X2avg(i) = X2avg(i)/nwalk;
xlabel('Step Number (Time)');
title('1-Dimensional Random Walk');

Accepted Answer

Benjamin Thompson
Benjamin Thompson on 9 Jun 2022
Try this to take advantage of vectorization in MATLAB. I may be confused about how you define "walks" and "steps", and whether you wanted the mean at each step or at the end. And if you want the first row of X to be the initial value zero that is a pretty small change.
close all;
n = 100; % number of walks
nwalk = 1000; % number of steps
X2 = rand(nwalk,n);
X3 = zeros(nwalk, n);
% Use index matrices to populate X3 with +1 and -1 as needed
Iright = X2 < 0.5;
Ileft = X2 > 0.5;
X3(Iright) = 1;
X3(Ileft) = -1;
% Sum along each column to create X
X = cumsum(X3, 1);
% Get the average of each row
Xavg = mean(X, 2);
% Get the variance of each row
Xvar = var(X, [], 2);
figure, plot(1:nwalk, X);
hold on;
plot(1:nwalk, Xavg, 'r--', 'LineWidth', 5)
plot(1:nwalk, Xvar, 'b--', 'LineWidth', 5)
hold off;

More Answers (1)

Image Analyst
Image Analyst on 9 Jun 2022
I've done lots of random walk demos. You might want to run the attached demos and see if any of them can be adapted or used.




Community Treasure Hunt

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

Start Hunting!