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

조회 수: 3 (최근 30일)
Thomas Veith
Thomas Veith 2019년 5월 30일
댓글: Star Strider 2019년 5월 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.
  댓글 수: 2
Thomas Veith
Thomas Veith 2019년 5월 30일
That's perfect, thank you!
Star Strider
Star Strider 2019년 5월 30일
As always, my pleasure!
You might also want to store your parameters, so you know what the solution used.

댓글을 달려면 로그인하십시오.

추가 답변 (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