Monday, June 25, 2012

MATLAB Code for 1-D Random Walk

See related post: 1-D Random Walk with Equal Probability

The previous post ran a simulation of one-dimensional random walk. Here is the MATLAB code that was run to achieve the the results, along with explanatory documentation:
numRuns = 100000;       %# of resets to position 0
numTrials = 1000000;    %# of trials per run
probLeft = 0.5;         %Here, equal probability going to left and right
zero = 0;               %# of times on position 0
negative = zeros(1);    %Array to keep track of # of times on negative numbers
positive = zeros(1);    %Similar array for positive numbers
for run = 1:numRuns     %Loop over the # of runs
    position = 0;       %Reset position for each run
    for count = 1:numTrials     %Loop iver the # of trials
        roll = rand;            %Simulated roll
        if roll < probLeft      %Going to the left
            position = position - 1;
        else                    %Going to the right
            position = position + 1;
        end
        if position < 0
            if abs(position) > length(negative) %If the position has never been visited before
                negative(abs(position)) = 0;    %Initialize the value to avoid error
            end
                negative(abs(position)) = negative(abs(position)) + 1;  %Increase counter
        elseif position > 0
            if position > length(positive)      %Similar tasks as above, but for positive positions
                positive(position) = 0;
            end
                positive(position) = positive(position) + 1;
        else
            zero = zero + 1;        %If landed on zero
        end
    end
end
y = [negative(end:-1:1) zero positive]; %# of times landed on each position
x = -length(negative):length(positive); %Position vector
plot(x,y)
xlabel('Position')
ylabel('Number of Times on the Position')
title('1 Dimensional Random Walk')

In this code, the variable 'probLeft' had a constant value of 0.5, reflecting on equal probability of going to the left and right. Further adjustments can tweak to define this variable to allow for the probability to reflect on the current position.