I am currently working on a complicated system of ~30 ODE's. To solve the system I have to use a stiff solver and calculate the jacobian of the system. I have written a successful series of functions that accomplishes this, however it requires that I define the ODE system in the "jacobian-calculating" function. Because of the complexity of my system I would prefer to create a stand-alone "model-function" that can be called by either my ode solver or my jacobian-calculating function.
I have included minimal examples of my code below. I believe my problem is with the line:
-----------------------------------------------------
SymbolicSystem = sym(NumericSystem);
-----------------------------------------------------
where "NumericSystem" is the handle for the anonymous function of my ode system. This line is contained in my function "testjacobian".
Does anyone know how to convert an anonymous function into a symbolic function? Or is there a better strategy for what I'm trying to do?
I do know that my code seems a bit contrived for this simple system, but this is because I have tried to capture the essential elements of the code used to solve my more complex system.
Any help would be greatly appreciated, Thanks in advance,
Laura
-----------------------------------------------------------------------------------
CODE:
-----------------------------------------------------------------------------------
function testdriver
a = 1;
b = 2;
c = 3;
d = 4;
param = [a b c d];
start1 = 0;
start2 = 1;
init = [start1, start2];
[t,x] = testsolver(param,init);
end
-----------------------------------------------------------------------------------
function [t,x]=testsolver(param,initial)
tspan = [0,10];
x1init = initial(1);
x2init = initial(2);
xinit = [x1init,x2init];
J = testjacobian(param);
CalcJac = @(t,x) call_on(J,x);
opts1 = odeset('Jacobian',CalcJac);
[t,x] = ode15s(@(t,x)testmodel(t,x,param),tspan,xinit,opts1);
end
function r = call_on(func, array)
vector = num2cell(array);
r = func(vector{:});
end
-----------------------------------------------------------------------------------
function xp = testmodel(t,x,param)
A = param(1);
B = param(2);
C = param(3);
D = param(4);
thing1 = x(1);
thing2 = x(2);
xp = zeros(2,1);
xp(1) = A*thing1^2 + B*thing2;
xp(2) = C*thing1 + D;
end
-----------------------------------------------------------------------------------
function Jacob=testjacobian(param)
syms tsym y1 y2
y = [y1 y2];
NumericSystem = @(t,x)testmodel(t,x,param);
SymbolicSystem = sym(NumericSystem);
SymbolicJacobian = jacobian(SymbolicSystem',y);
Jacob = matlabFunction(SymbolicJacobian,'var',y);
end