
% Brownian motion simulation

% Time parameters
T = 4.0;   % Time interval
Nt = 41;   % number of sampling points
Dt = T / (Nt - 1);  % time step
% sampling times
times = linspace(0.0, T, Nt);

% Stochastic parameters
Np = 60;       % number of paths
mu = 0.2;      % drift
sigma = 2.0;   % diffusion
stdev = sigma*sqrt(Dt);

X = zeros(Nt, Np);

% Drifting Gaussian variable 
for it = 2:Nt
   X(it,:) = X(it-1,:) + normrnd(mu*Dt, stdev, 1,Np);
end;
plot(times, X)
xlabel('time')
ylabel('distance')
mean(X(Nt,:))
std(X(Nt,:))

pause

% Standard Gaussian variable
for it = 2:Nt
   X(it,:) = X(it-1,:) + mu*Dt + stdev*normrnd(0.0, 1, 1,Np);
end;
plot(times, X)
xlabel('time')
ylabel('distance')
mean(X(Nt,:))
std(X(Nt,:))

