Search code examples
matlabodenumerical-integrationode45

Matlab ode45 vs. ode23, different solutions


I used ode45 and ode23 for a set of non-stiff differential equations. However, both methods converge to a slightly different solution. How can I find out which one is correct? See attached plot where blue is ode45, red is ode23. The dashed lines are the final values for each solver. Also, ode15s is a bit different (less than 1 m)...

enter image description here


Solution

  • Matlab's ODE solvers are adaptive so one specifies tolerances rather than a step size (see also this answer). Given the code in the PDF linked in the comments, if you specify a smaller value for the relative tolerance, the solutions from ode45 and ode23 will converge after the same amount of time. You can use odeset to set 'RelTol':

    ...
    opts = odeset('RelTol', 1e-12);
    [t, oput] = ode23(@(t,y)secondode(t,y,C,g), tspan, IC, opts);
    ...
    

    Note that I also got rid of the global variables used in the linked code (they're bad and inefficient). You also need to change the function definition for secondode to:

    function z = secondode(t, indata, C, g)
    ...