Calling ode45 with cellfun ignores TSPAN
Show older comments
I'm trying to solve an ODE several thousand times using different parameters each time. I was hoping to avoid using a loop so tried cellfun. However, when using this function my TSPAN argument seems to be ignored.
The derivative for a simple Lotka-Volterra system is as follows (which I'm storing in a file LV.m):
% ODE defining the system
function derivs = LV(t, State, Pars)
% Assignments left in for clarity
a = Pars(1);
b = Pars(2);
x = State(1);
y = State(2);
dx = a*x - x*y;
dy = b*x*y - y;
derivs = [dx; dy];
I can solve the ODE once simply using:
rng(19)
pars = rand(2, 1)*2 - 1;
Y0 = [1.0, 0.5];
eval_times = [0, 1.2, 2.4, 3.9, 5.7, 7.5, 9.6, 11.9, 14.5];
[TOUT, YOUT] = ode45(@(t, y)LV(t, y, pars), eval_times, Y0);
>> length(TOUT)
ans =
9
However, if I try to solve this multiple times, with different input parameters, then the TSPAN argument is ignored:
N = 10;
pars = rand(2, N)*2 - 1;
cellpars = mat2cell(pars, [2], ones(N,1));
out = cellfun(@(x) ode45(@(t, y)LV(t, y, x), eval_times, Y0), ...
cellpars, 'UniformOutput', false);
>> length(out{1}.x)
ans =
19
Any ideas on how to run this multiple times in such a manner or is this an instance where it is better to simply use a loop?
Footnote
I ask because, in a very rough test, the call to cellfun seems to be significantly faster than using a loop. Here's a test running the same parameter values multiple times:
pars = ones(2, 1);
tic
for i = 1:10000
[TOUT, YOUT] = ode45(@(t, y)LV(t, y, pars), eval_times, Y0);
end
toc
>> Elapsed time is 20.486351 seconds.
N = 10000;
pars = ones(2, N);
cellpars = mat2cell(pars, [2], ones(N,1));
tic
out = cellfun(@(x) ode45(@(t, y)LV(t, y, x), eval_times, Y0), ...
cellpars, 'UniformOutput', false);
toc
>> Elapsed time is 14.965086 seconds.
Accepted Answer
More Answers (1)
Walter Roberson
on 28 Mar 2017
0 votes
I am not getting the result you see -- the number of time points I am getting out are as expected.
However, what I am seeing is that over the random parameters you are generating, that the ode is encountering a singularity. This happens, for example, at [1.80088819535342 -1.86221567798836] . The correlation I seem to notice is that it gets closer to a singularity as the second parameter gets more negative.
Categories
Find more on Ordinary Differential Equations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!