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

5 visualizaciones (últimos 30 días)
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 comentario
Thomas Veith
Thomas Veith el 30 de Mayo de 2019
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);

Iniciar sesión para comentar.

Respuesta aceptada

Star Strider
Star Strider el 30 de Mayo de 2019
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 comentarios
Thomas Veith
Thomas Veith el 30 de Mayo de 2019
That's perfect, thank you!
Star Strider
Star Strider el 30 de Mayo de 2019
As always, my pleasure!
You might also want to store your parameters, so you know what the solution used.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Ordinary Differential Equations en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by