% begin definitions and initialisation T = 500; % define running time T N = 10; % define number of realisations N X = zeros(N,T); % pre-allocate array to store realisations % Should have N rows of length T % i.e. X(2,3) should give value of realisation 2 at time 3 t = [1:T]; % create integer array of times X(:,1) = 0; % initial position is always zero % end initialisation % begin simulation for j =1:N % begin loop over realisations for i=1:T-1 % begin loop through timesteps r = rand(); % create random variable if r < 0.8; X(j,i+1) = X(j,i); % next position is the same elseif r < 0.9 X(j,i+1) = X(j,i) - 1; % next position is back else X(j,i+1) = X(j,i) + 1; % next position is forward end end % end loop through timesteps end % end loop over realisations % end simulation % begin plotting % there are many nice ways to produce handsome plots in MATLAB % shown here are just my personal preferences figure('Color',[1 1 1]); % create figure with white background set(gca,'FontSize',20) % set fontsize for axes plot(X','LineWidth',2) % plot data N.B. Transpose required to plot X vs T hold on; % hold the plot grid on; % plot gridlines (looks nice) plot(t,sqrt(t),'k',t,-sqrt(t),'k','LineWidth',2) % plot variance axis([0,T,-1*T/20,+1*T/20]) % x-axis between 0 and T % N.B. limits of y-axis have been 'fudged' a bit here... xlabel('Time t','FontSize',20);ylabel('Position x','FontSize',20); % N.B. plotting the character string 'LineWidth' followed by a 2 % makes the plot look a little nicer (in my view) and easier to read, % however your mileage may vary. % end plotting