0

I want to plot multiple realizations of a stochastic process in matlab. For a single realization I have the following code:

N = 80; 
T = dt*N; 
dWt = zeros(1,N);             
S= repmat(S0,1,N);

S(1) = S0;

dWt = sqrt(dt) * randn;

for t=2:N
dWt(t) = sqrt(dt)*randn;
 dSt = k*(mu-S(t-1))*dt + sigma*S(t-1)*dWt(t);
 S(t) = S(t-1)+dSt;

end
 plot(handles.pMeasure, [0:dt:T],[S0,S]);   

I want to replicate this loop n times and plot the results in one plot.

user137425
  • 429
  • 6
  • 17

1 Answers1

1

You could add an additional for loop, but it would be best to vectorize everything and calculate all n instances at once:

k = ...
mu = ...
sigma = ... 
S0 = ...    % Initial condition
dt = ...    % Time step
n = ...     % Number of instances
N = 80;     % Number of time steps, not counting initial condition
T = dt*N;   % Final time

rng(1);                          % Always seed random number generator
dWt = sigma*sqrt(dt)*randn(n,N); % Calculate Wiener increments
S = zeros(n,N+1);                % Allocate
S(:,1) = S0;                     % Set initial conditions

for t = 2:N+1
    S(:,t) = S(:,t-1) + k*(mu-S(:,t-1))*dt + S(:,t-1).*dWt(:,t-1);
end

plot(handles.pMeasure,0:dt:T,S)

There are further ways to optimize this if want or you can also try sde_euler in my SDETools Matlab toolbox:

k = ...
mu = ...
sigma = ...
dt = ...    % Time step
n = ...     % Number of instances
N = 80;     % Number of time steps, not counting initial condition
T = dt*N;   % Final time

f = @(t,y)k*(mu-y); % Diffusion function
g = @(t,y)sigma*y;  % Drift function
t = 0:dt:T;         % Time vector
S0 = zeros(n,1);    % Initial conditions

opts = sdeset('RandSeed',1,...
              'SDEType','Ito'); % Set random seed, specify Ito SDE
S = sde_euler(f,g,t,S0,opts);   % Simulate

plot(t,S)
horchler
  • 18,384
  • 4
  • 37
  • 73