Search code examples
matlabvariancerandom-walk

Variance in random Walk with Matlab


I'm new to the forum and a beginner in programming.

I have the task to program a random walk in Matlab (1D or 2D) with a variance that I can adjust. I found the code for the random walk, but I'm really confused where to put the variance. I thought that the random walk always has the same variance (= t) so maybe I'm just lost in the math.

How do I control the variance?


Solution

  • For a simple random walk, consider using the Normal distribution with mean 0 (also called 'drift') and a non-zero variance. Notice since the mean is zero and the distribution is symmetric, this is a symmetric random walk. On each step, the process is equally like to go up or down, left or right, etc.

    One easy way:
    Step 1: Generate each step
    Step 2: Get the cumulative sum

    This can be done for any number of dimensions.

    % MATLAB R2019a
    drift = 0;
    std = 1;         % std = sqrt(variance)
    pd = makedist('Normal',drift,std);
    
    % One Dimension
    nsteps = 50;
    Z = random(pd,nsteps,1);
    X = [0; cumsum(Z)];
    plot(0:nsteps,X)          % alternatively:  stairs(0:nsteps,X)   
    

    And in two dimensions:

    % Two Dimensions
    nsteps = 100;
    Z = random(pd,nsteps,2);
    X = [zeros(1,2); cumsum(Z)];
    

    Simple two dimensional random walk with each step being from Normal(0,1).

    % 2D Plot
    figure, hold on, box on
    plot(X(1,1),X(1,1),'gd','DisplayName','Start','MarkerFaceColor','g')
    plot(X(:,1),X(:,2),'k-','HandleVisibility','off')
    plot(X(end,1),X(end,2),'rs','DisplayName','Stop','MarkerFaceColor','r')
    legend('show')
    

    The variance will affect the "volatility" so a higher variance means a more "jumpy" process relative to the lower variance.

    Two separate Gaussian two dimensional random walks with difference variances.

    Note: I've intentionally avoided the Brownian motion-type implementation (scaling, step size decreasing in the limit, etc.) since OP specifically asked for a random walk. A Brownian motion implementation can link the variance to a time-index due to Gaussian properties.


    The OP writes:

    the random walk has always the same variance

    This is true for the steps (each step typically has the same distribution). However, the variance of the process at a time step (or point in time) should be increasing with the number of steps (or as time increases).


    Related:
    MATLAB: plotting a random walk