矩阵模拟(随机)



假设我有一个形式的 SDE 离散系统

x(:, t+1) = x(:, t) + f1(x(:, t)).*x(:, t)*dt + f2(x(:, t))./(x(:, t).*y(:, t))* sqrt(dt)*rand1;
y(:, t+1) = f2(x(:, t)).*y(:, t)./x(:, t)*dt + f1(x(:, t)).*y(:, t)*sqrt(dt)*rand2;

我想使用 10000 条轨迹模拟系统,

对于时间 t = 100 天,使得:从星期一到星期五,

f1(x(:, t)) = 2*x(:, t).^2./(y(:, t) + x(:, t) + c)

f2(x(:, t)) = y(:, t).^2;鉴于周六和周日

f1(x(:, t)) = x(:, t)./y(:, t)f2(x(:, t)) = y(:, t);如何模拟 SDE 系统?

这是我的方法

dt = 0.01;
time = 100;
num_iteration = ceil(time / dt);
num_trajectory = 10000; 
%% Initial Values
y0 = 1; 
x0 = 1;
y = zeros(num_trajectory, num_iteration) + y0; 
x = zeros(num_trajectory, num_iteration) + x0; 
days = 0;
for t=1: num_iteration
current_time = t * dt;
rand1 = randn(num_trajectory, 1);
rand2 = randn(num_trajectory, 1);
if ceil(current_time) == current_time
days = days+1;
if (mod(days, 7) | mod(days+1, 7)) == 0
f1 = 2*x(:, t).^2./(y(:, t) + x(:, t) + c);
f2 = y(:, t).^2;
else
f1 = x(:, t)./y(:, t);
f2 = y(:, t); 
end
end
x(:, t+1) = x(:, t) + f1*x(:, t)*dt + f2/(x(:, t).*y(:, t))* sqrt(dt)*rand1;
y(:, t+1) = f2*y(:, t)./x(:, t)*dt + f1*y(:, t)*sqrt(dt)*rand2;   
end

你的方法似乎很好。不过,您的代码中存在逻辑错误。在行中

if (mod(days, 7) | mod(days+1, 7)) == 0

表达式(mod(days, 7) | mod(days+1, 7))的计算结果将始终为 1(尝试找出为什么会这样),因此(mod(days, 7) | mod(days+1, 7)) == 0将始终为 false,并且您的 if 语句将始终将控制权传递给else部分。

因此,这应该是这样的

if mod(days, 7) == 0 || mod(days+1, 7) == 0

但这也令人困惑(并且您尚未在代码中记录工作日"0"是哪一天)。

更清楚的是:

if (
mod (days, 7) == 0 % day is a sunday
|| 
mod (days, 7) == 6 % day is a saturday
)
% do stuff
else
% do other stuff
end 

更好的是,创建一个小函数isWeekend为您执行该测试,从而产生超清晰的代码,例如

if isWeekend(days)
% do stuff
else 
% do other stuff
end

最新更新