在同一图中绘制随机过程的实现

时间:2015-12-07 21:55:08

标签: matlab plot stochastic-process

我想在matlab中绘制随机过程的多个实现。对于单个实现,我有以下代码:

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]);   

我想复制这个循环n次并将结果绘制在一个图中。

1 个答案:

答案 0 :(得分:1)

您可以添加额外的for循环,但最好将所有内容矢量化并一次计算所有n个实例:

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)

如果需要,还有其他方法可以优化此功能,或者您也可以在我的sde_euler Matlab工具箱中尝试SDETools

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)