# solving differential equations with jacobian pattern

I'm trying to compare the simulation time for solving a system of differential equations with and without jacobian pattern for a toy model using ode15s in MATLAB.

global mat1 mat2
mat1=[
1    -2     1     0     0     0     0     0     0     0;
0     1    -2     1     0     0     0     0     0     0;
0     0     1    -2     1     0     0     0     0     0;
0     0     0     1    -2     1     0     0     0     0;
0     0     0     0     1    -2     1     0     0     0;
0     0     0     0     0     1    -2     1     0     0;
0     0     0     0     0     0     1    -2     1     0;
0     0     0     0     0     0     0     1    -2     1;
];

mat2 = [
1    -1     0     0     0     0     0     0     0     0;
0     1    -1     0     0     0     0     0     0     0;
0     0     1    -1     0     0     0     0     0     0;
0     0     0     1    -1     0     0     0     0     0;
0     0     0     0     1    -1     0     0     0     0;
0     0     0     0     0     1    -1     0     0     0;
0     0     0     0     0     0     1    -1     0     0;
0     0     0     0     0     0     0     1    -1     0;
];

x0 = [1 0 0 0 0 0 0 0 0 0]';
tspan = 0:0.01:5;

y = sym('y', [10 1]);
s = mat1*y + mat2*y;
J = jacobian(s, y);
[jr, jc] = size(J);
jpattern = sparse(jr, jc);
jpattern(find(J~=0)) = 1;
jac = sparse(10,10);
jac(2:9, :) = jpattern;
jac(10,:) = [0 0 0 0 0 0 0 0 1 1];

options = odeset('Stats', 'on', 'JPattern', jac);

ttic = tic();
[t, sol]  =  ode15s(@(t,x) fun(t,x), tspan , x0, options);
ttoc = toc(ttic)
fprintf('runtime %f seconds ...\n', ttoc)
plot(t, sol)

function f = fun(t,x)
global mat1 mat2
f(1,1) = 0;
f(2:9,1) = mat1*x + mat2*x;
f(10,1) = 2*(x(end-1) - x(end));
end


I expected that the simulation time will decrease when the jacobian pattern is specified  [t, sol] = ode15s(@(t,x) fun(t,x), tspan , x0, options) . However, I find that the simulation takes longer when jpattern is specified.

Clarifications on why the simulation time increases when jpattern is given will be helpful.

• Your problem is very small, and your jacobian is constant as your problem is linear, so it's only evaluated once. Try a nonlinear problem instead, with more variables, and will see a benefit from this technique if your Jacobian structure is "sparse enough". – Laurent90 Feb 17 at 18:15