我目前有模拟几何布朗运动的代码,由 http://www-math.bgsu.edu/~zirbel/sde/matlab/index.html 提供.
但是,我想生成 1,000 个模拟并将它们显示在图表中。
我目前生成单个模拟的代码如下:
% geometric_brownian(N,r,alpha,T) simulates a geometric Brownian motion
% on [0,T] using N normally distributed steps and parameters r and alpha
function [X] = geometric_brownian(N,r,alpha,T)
t = (0:1:N)'/N; % t is the column vector [0 1/N 2/N ... 1]
W = [0; cumsum(randn(N,1))]/sqrt(N); % S is running sum of N(0,1/N) variables
t = t*T;
W = W*sqrt(T);
Y = (r-(alpha^2)/2)*t + alpha * W;
X = exp(Y);
plot(t,X); % plot the path
hold on
plot(t,exp(r*t),':');
axis([0 T 0 max(1,exp((r-(alpha^2)/2)*T+2*alpha))])
title([int2str(N) '-step geometric Brownian motion and its mean'])
xlabel(['r = ' num2str(r) ' and alpha = ' num2str(alpha)])
hold off
最佳答案
该代码不能直接用于模拟 1,000 条路径/模拟。不幸的是,它还没有被矢量化。完成您想要的操作的最简单方法是使用 for
循环:
N = 1e3;
r = 1;
alpha = 0.1;
T = 1;
npaths = 1e3; % Number of simulations
rng(0); % Always set a seed
X = zeros(N+1,npaths); % Preallocate memory
for i = 1:n
X(:,i) = geometric_brownian(N,r,alpha,T);
hold on
end
t = T*(0:1:N).'/N;
plot(t,exp(r*t),'r--');
这相当缓慢且低效。您将需要对该函数进行大量修改才能对其进行矢量化。可以提高性能的一件事是,如果您至少从函数内部删除绘图代码并在循环后单独运行它。
另一种选择可能是使用 sde_gbm
在我的SDETools toolbox中起作用,它是完全矢量化的并且速度更快:
N = 1e3;
r = 1;
alpha = 0.1;
T = 1;
npaths = 1e3; % Number of simulations
t = T*(0:1:N)/N; % Time vector
y0 = ones(npaths,1); % Vector of initial conditions, must match number of paths
opts = sdeset('RandSeed',0,'SDEType','Ito'); % Set seed
y = sde_gbm(r,alpha,t,y0,opts);
figure;
plot(t,y,'b',t,y0*exp(r*t),'r--');
xlabel('t');
ylabel('y(t)');
title(['Geometric Brownian motion and it's mean: ' int2str(npaths) ...
' paths, r = ' num2str(r) ', \alpha = ' num2str(alpha)]);
无论哪种情况,都会得到类似这样的图
关于matlab - 在 MATLAB 中模拟 1,000 个几何布朗运动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18684998/