Random Walk in MATLAB for any Number of Dimensions

Previously, we showed how to perform a random walk in one dimension and in two dimensions using MATLAB’s rand function. Now let’s look at the general case, where the user can specify d > 1 dimensions and n >= 1 step. Here’s a sample gif of how this would look in three dimensions:


Let’s once again initialize our function “random_walk” and do error checking on the three input arguments.

% Random Walk in MATLAB
function position = random_walk(numSteps, numDimensions, plotResults)

% default values
if nargin < 3
    plotResults = false;
end
if nargin < 2
    numDimensions = 2;
end
% Use 40 as default number of steps
if nargin < 1
    numSteps = 40;
end

This time we will utilize rand to generate up to 2*numDimensions integer values. This is because in a random walk, we can move in either -1 or +1 directions in any of the dimensions.
Based on this fact, we will update our random direction array to be 1 or -1 depending on the integer values generated:

% initialize the values with zeros
randValues = zeros(numSteps, numDimensions);
% randomize possible directions (2*numDimensions)
randDirection = round((2*numDimensions-1)*rand(numSteps,1))+1;
for k = 1:numDimensions
    randValues(randDirection == 2*k-1,k) = 1;
    randValues(randDirection == 2*k,k) = -1;
end

Here’s an example of what the randValues and randDirection arrays would look like for 10 steps in 3 dimensions:

>> [randValues randDirection]

ans =

    -1     0     0     2
     0    -1     0     4
     1     0     0     1
     0     0     1     5
     0     0     1     5
     0     0    -1     6
     0     0    -1     6
     0    -1     0     4
    -1     0     0     2
    -1     0     0     2

As you can see, we randomized the fourth column to be integer values from 1 to 6. These correspond to +1 or 1 movement in x (1 or 2), in y (3 or 4), or in z (5 or 6).

Finally, we update the position, starting from the origin:

% 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

And thats it! Here would be the position values for the above 10 step test:

position =

     0     0     0
    -1     0     0
    -1    -1     0
     0    -1     0
     0    -1     1
     0    -1     2
     0    -1     1
     0    -1     0
     0    -2     0
    -1    -2     0
    -2    -2     0

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.