How can I solve this ODE 1000 times with random variables?

3 次查看(过去 30 天)
So I have this code:
tspan=[1 7];A0=rand;P0=rand;g=rand;p=rand;B=rand;
[t,x] = ode45(@(t,x) [-g*x(1) + p*x(1); -x(1)*x(2)+ B*x(2)], tspan, [A0 P0])
And it works perfectly.
But what I want to do is run it 1000 times and change the random inputs each time, and generate new solutions every time. I've tried using the following:
n = 1000;
result = zeros(n,1);
for k=1:n
tspan=[1 7];A0=rand;P0=rand;g=rand;p=rand;B=rand;
[t,x(n)] = ode45(@(t,x) [-g*x(n(1)) + p*x(n(1)); -x(n(1))*x(n(2))+ B*x(n(2))], tspan, [A0 P0])
result(k) = x(n);
end
But I get the error
Index exceeds the number of array elements (2).
Error in @(t,x)[-g*x(n(1))+p*x(n(1));-x(n(1))*x(n(2))+B*x(n(2))]
Error in odearguments (line 90)
f0 = feval(ode,t0,y0,args{:}); % ODE15I sets args{1} to yp0.
Error in ode45 (line 115)
odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options, varargin);
Any advice?
  1 个评论
Thomas Veith
Thomas Veith 2019-5-30
Alternatively, if I try this:
n = 1000;
result = zeros(n,1);
for k=1:n
tspan=[1 7];A0=rand(n);P0=rand(n);g=rand(n);p=rand(n);B=rand(n);
[t,x] = ode45(@(t,x) [-g*x(1) + p*x(1); -x(1)*x(2)+ B*x(2)], tspan, [A0 P0])
result(k) = x(n);
end
I get the following error:
Error using odearguments (line 93)
@(T,X)[-G*X(1)+P*X(1);-X(1)*X(2)+B*X(2)] must return a column vector.
Error in ode45 (line 115)
odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options, varargin);

请先登录,再进行评论。

采纳的回答

Star Strider
Star Strider 2019-5-30
You coded your differential equation correctly. Your ‘x’ variable has only two elements, so you cannot use ‘n’ (or ‘k’) to subscript them.
See if this does what you want:
n = 1000;
result = cell(n,1);
for k=1:n
tspan=[1 7];A0=rand;P0=rand;g=rand;p=rand;B=rand;
[t,x] = ode45(@(t,x) [-g*x(1) + p*x(1); -x(1)*x(2)+ B*x(2)], tspan, [A0 P0]);
result{k} = x;
end
Note that because the time vector can change between your ode45 calls, a cell array is most appropriate. If you want a specific number of values to be returned each iteration, define ‘tspan’ as a vector of more than two elements.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Ordinary Differential Equations 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by