One dimensional random walk in MATLAB

We’re going to do a series of posts on Matlabgeeks to demonstrate how MATLAB is a wonderful option for running simulations. As a precursor to this, let’s look at a stochastic process known as a random walk. Briefly, such a process, in one-dimensional space, assumes equal probability of one of two possibilities occurring. For example, if you were to flip a fair coin multiple times, a random walk would demonstrate the total sum of heads and tails that are turned up after n flips. We will demonstrate how to model this process on the integer number line, with heads moving in the +1 direction and tails moving in the -1 direction.

Let’s first setup our function random_walk.m, taking in three input arguments:

% Random Walk in MATLAB
function position = random_walk(numSteps, numDimensions, plotResults)
% Vipul Lugade
% Oct 1, 2018
% matlabgeeks.com

% default values
if nargin < 3
    plotResults = false;
end
% Default the random walk to 2 Dimensions
if nargin < 2
    numDimensions = 2;
end
% Use 40 as default number of steps
if nargin < 1
    numSteps = 40;
end

The ‘numSteps’ variable specifies how many decisions (coin flips in 1D) to perform. The ‘numDimensions’ variable indicates how many dimensions to run the random walk across. For this post we will look at the simple case of 1 Dimensions, but we will show 2D/3D in a future post as well. Finally, the ‘plotResults’ variable is a boolean specifying whether to plot the results of the random walk.

In order to generate a random sequence of events, we will utilize MATLAB’s rand function, which we have previously discussed. For values < 0.5, we will set the value to -1 and for those greater than or equal to 0.5, we will set the value to 1.

% setup random walk values
randValues = round(rand(numSteps, numDimensions));

% One dimensional random walk
if numDimensions == 1
    randValues(randValues == 0) = -1;
% Two dimensional random walk
elseif numDimensions == 2
end

Now, perform the walk and calculate where on the number line we will be after n flips:

% start at origin and initialize the position
position = zeros(numSteps+1, numDimensions);
for k = 2:numSteps+1
    position(k,:) = position(k-1,:) + randValues(k-1,:);
end

Let’s look at an example, when running the following 1 dimensional random walk with 40 steps:

position = random_walk(40, 1, true)

One dimensional random walk in MATLAB

Stay tuned for further posts! If you have any comments or questions, don’t hesitate to contact us.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.