Search code examples
matlabodenumerical-analysis

Solve a matrix valued differential equation in Matlab


I am trying to solve a particular system of ODE's dF/dt = A*F, F_initial = eye(9). Being a Matlab novice, I am trying to somehow use the implemented ode45 function, and I found useful advises online. However, all of them assume A to be constant, while in my case the matrix A is a function of t, in other words, A changes with each time step.

I have solved A separately and stored it in a 9x9xN array (because my grid is t = 0:dt:2, N=2/dt is the number of time-steps, and A(:,:,i) corresponds to it's value at the i-th time step). But I can't implement this array in ode45 to eventually solve my ODE.

Any help is welcomed, and please tell me if I have missed anything important while explaining my problem. Thank you


Solution

  • First of all, F must be a column vector when using ode45. You won't ever get a result by setting F_initial = eye(9), you'd need F = ones(9,1).

    Also, ode45 (documentation here, check tspan section) doesn't necessarily evaluate your function at the timesteps that you give it, so you can't pre-compute the A matrix. Here I'm going to assume that F is a column vector and A is a matrix which acts on it, which can be computed each timestep. If this is the case, then we can just include A in the function passed to ode45, like so:

    F_initial = ones(9,1);
    dt = 0.01;
    tspan = 0:2/dt:2;
    [t, F] = ode45(@(t,F) foo(t, F, Ainput), tspan, F_initial);
    
    function f = foo(t, F, Ainput)
        A = calculate_A(t, Ainput);
        f = A*F;
    end
    
    function A = calculate_A(t, Ainput)
        %some logic, calculate A based on inputs and timestep
        A = ones(9,9)*sqrt(t)*Ainput;
    end
    

    The @(x) f(x,y) basically creates a new anonymous function which allows you to treat y as a constant in the calculation.

    Hope this is helpful, let me know if I've misunderstood something or if you have other questions.