MATLAB: What is mistake in the code? i want to simulation brownian motion.

simulation

T = 5; N = 10000; Delta = T/N; M=5;
W = zeros(M,N); Wtemp = 0; Winc = sqrt(Delta)*randn(M,N); for i=1:M*N W(i) = Wtemp + Winc(i); Wtemp = W(i); end x1=W(1,:); x2=W(2,:); x3=W(3,:); x4=W(4,:); x5=W(5,:); figure(1) plot(0:Delta:T,[0 x1]) hold on plot(0:Delta:T,[0 x2]) hold on plot(0:Delta:T,[0 x3]) hold on plot(0:Delta:T,[0 x4]) hold on plot(0:Delta:T,[0 x5]) hold off

Best Answer

I had posted an answer here yesterday, but it vanished?! Strange. I try it again:
Your code is one random walk over N*M steps. You draw this such that M=5 lines are drawn through the steps 1:5:end, 2:5:end, etc. The code works correctly, but I assume, you want five different random walks over N steps. Then:
T = 5;
N = 10000;
Delta = T/N;
M = 5;
Winc = sqrt(Delta) * randn(N, M);
Winc(1, :) = 0; % Start at zero
W = cumsum(Winc, 1);
plot(linspace(0, T, N), W);
Calling cumsum is nicer, faster and easier than a loop. But if there is any need to use a loop:
Winc = sqrt(Delta) * randn(N, M);
W = zeros(N, M);
for k = 2:N % First element remains zero
W(k, :) = W(k-1, :) + Winc(k, :);
end
plot(linspace(0, T, N), W);
Related Question