how to write differential equations as a function to be used in ode15s in matlab

To write a system of differential equations as a function to be used with the ode15s solver in MATLAB, you follow these steps:

  1. Define a function that represents your system of differential equations. This function should take two input arguments: t, the current time, and y, the vector of the current values of the dependent variables. The function should return a column vector representing the derivatives of the dependent variables at the given time. Let's call this function odesystem.

    main.m
    function dydt = odesystem(t, y)
        % Define the parameters and variables of your system
        a = 1;
        b = 2;
        c = 3;
    
        % Extract the dependent variables from the y vector
        x = y(1);
        y = y(2);
    
        % Compute the derivatives of the dependent variables
        dxdt = a * x - b * y;
        dydt = c * x + y;
    
        % Return the derivative vector
        dydt = [dxdt; dydt];
    end
    
    378 chars
    18 lines
  2. Now, you can use the ode15s solver to numerically solve your system of differential equations. Remember to provide the initial conditions for the dependent variables and specify the time span of the simulation.

    main.m
    % Define the initial conditions
    initialConditions = [0; 0];
    
    % Define the time span
    tspan = [0, 10];
    
    % Solve the system of differential equations
    [t, y] = ode15s(@odesystem, tspan, initialConditions);
    
    202 chars
    9 lines

    In this example, t will be the vector of time points at which the solver evaluated the solution, and y will be the matrix where each row corresponds to the values of the dependent variables at the corresponding time point.

That's it! You've written your differential equations as a function to be used with ode15s in MATLAB. Make sure to adjust the odesystem function to represent your specific system of differential equations.

gistlibby LogSnag