MATLAB: How to generate a MEX function for a parameterized MATLAB function and solve it using the ODE15S solver in MATLAB 8.1 (R2013a)

matlab coder

I am trying to solve a function using the ODE15S solver. I first create a mex function and then pass it to the ODE15S solver.
However, I want this function to be parameterized so that I can analyze solutions for different sets of parameters.

Best Answer

The following example demonstrates how to solve a parameterized function using the ODE15S solver.
Let us assume that we would like to solve the following function for different sets of values for parameters "A" and "B"
function dy = rigid(t,y,A,B)
dy = zeros(3,1); % a column vector
dy(1) = y(2) * y(3);
dy(2) = A * y(1) * y(3);
dy(3) = B * y(1) * y(2);
The following lines of code can be implemented to solve the above function for different parameter sets:
% Generate the mex function for the function RIGID
codegen -o rigid_mex rigid.m -args {1, ones(3,1), 1, 1};
% Declare parameters A and B
A = [-1 -1.5 -1.7];
B = [-0.51 -.35 -0.70];
% Set Solver options for ODE15S
options = odeset('RelTol',1e-4,'AbsTol',[1e-4 1e-4 1e-5]);
% Declare T and intial value for Y
T = [0 12];
Y = [0 1 1];
% Solve the equation using ODE15S
for i=1:3
[t,y] = ode15s(@(T,Y)rigid_mex(T,Y,A(i),B(i)),T,Y,options);
% this works as ODE15s only needs T and Y as inputs, but A and B can still be passed as shown above using Anonymous Functions.
figure(i)
plot(t,y(:,1),'-',t,y(:,2),'-.',t,y(:,3),'.')
end
Related Question