Search code examples
matlabodedifferential-equations

Change value of variable at each time step - Matlab ODE function


I have the following system of differential equations to simulate in a .m file:

function dx = odefun(t,x)
    % display(x(1));
    % y = 5; 
    dx = [x(2); - y - 3*x(2) - 2*x(1)];
end

I am simulating the system running another .m file with the code below:

[t,x] = ode45(@odefun, [0 10], [0;0]);
% display(x(:,1));
plot(t,x(:,1));

My problem is that I want the value of y parameter, which happens to be the output of my system, to change in each time step while the ode(...) function is executing. I tried by sending another argument like this:

[t,x] = ode45(@odefun, [0 10], [0;0], [some_elements]);
function dx = odefun(t,x,y)

but I get the error: Not enough input arguments. Truth is that I want y parameter to take one value at each time step from a vector with a hundred elements. Any help would be greatly appreciated.


Solution

  • Not tested on Matlab but just to help and mainly wrapped up from https://fr.mathworks.com/help/matlab/ref/ode45.html#bu00_4l_sep_shared-options ODE with Time-Dependent Terms

    function dx = odefun(t,x,y,yt)
        f = interp1(yt,y,t);
        dx = [x(2); - f - 3*x(2) - 2*x(1)];
    end
    
    %define your array (or even function) y(yt)
    yt = 0.0:0.1:10.0;
    y = array; % array being your array of input values. (should contain the corresponding value for 0.0:0.1:10.0
    
    [t,x] = ode45(@(t,x) odefun(t,x,y,yt), [0.0 10.0], [0;0]);
    

    or try the following if you want specific time steps included in your result :

    [t,x] = ode45(@(t,x) odefun(t,x,y,yt), yt, [0;0]);
    

    You can also do, to be sure to have your solution corresponding to 0.0:0.1:10.0,

    x100 = interp1(t,x,yt);