Previously we described what a random walk is and demonstrated some simple code to perform this walk in one dimensional space. Today we will provide some simple code for how to perform such a walk in two-dimensional space. In the following post, we’ll look at the general case, and then we’ll get into some simulations. Here’s a sample of how our output will look like:
Just like before, we’ll first begin by initializing our function “random_walk”, do some simple argument error checking, and utilize MATLAB’s built-in “rand” and “round” functions.
% 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 % setup random walk values randValues = round(rand(numSteps, numDimensions));
While in the one-dimensional case, we just had to worry about movement of -1 or 1 along the single axis, now we have four possibilities, specifically [1,0], [-1,0], [0,1], and [0,-1], in the (x,y) directions, respectively. Here’s how we will handle having these four possibilities. We’ll search through our array “randValues” and replace any (0,0) or (1,1) entries with (-1,0) and (0,-1). We can use the built-in MATLAB function repmat to do this for all instance of (0,0) or (1,1) in the array.
% One dimensional random walk if numDimensions == 1 randValues(randValues == 0) = -1; % Two dimensional random walk elseif numDimensions == 2 % lets do the following conversions in 2D % [0, 0] move backwards in x, i.e. [-1, 0] negX = ismember(randValues,[0 0], 'rows'); randValues(negX,:) = repmat([-1 0], sum(negX), 1); % [1, 0] move forwards in x % [0, 1] move forwards in y % [1, 1] move backwards in y, i.e [0, -1] negY = ismember(randValues,[1 1], 'rows'); randValues(negY,:) = repmat([0 -1], sum(negY), 1); end
Just like before, we now increment our position with each step:
% 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 now the example we show at the beginning of this post is as follows:
position = random_walk(40,2,true) position = 0 0 0 -1 -1 -1 -1 0 -1 1 -2 1 -2 2 -2 1 -2 0 -2 -1 -2 0 -3 0 -4 0 -3 0 -4 0 -4 1 -5 1 -4 1 -3 1 -2 1 -3 1 -2 1 -2 2 -1 2 -2 2 -2 1 -2 2 -3 2 -2 2 -1 2 -2 2 -2 1 -1 1 -1 2 -1 3 -2 3 -3 3 -2 3 -1 3 0 3 0 2
Stay tuned for more, and let us know if you have any comments!