Search code examples
matlabdifferential-equations

Initial Condition for ode45?


I need to use ode45 to find approximate values of the solution at t=1, 1.5, and 3 and then plot the solution on [0.5,4]

    %% 7) exp(y)+(t*(exp(y)-sin(y))*y'=0, y(2)=1.5
% 7a) Find approximate values of the solution at t=1, 1.5, and 3 then plot
% the solution on [0.5,4].

[t,y]=ode45(@(t,y) -exp(y)./(t.*(exp(y))-sin(y)),0.5:.2:4,1.5)

As shown above, the initial condition starts at t =2 and not 0. How do you use ode45 with an initial condition starting at t=2? I also have to find approximate values below t=2 as well.


Solution

  • Since y(2) = 1.5 means at t=2, y = 1.5, you can first use ode45 to get the answers from t = 2 to t = 4 from below code.

    tspan1 = [ 2 : 0.05 : 4];
    [t1,y1]=ode45(@(t,y) -exp(y)./(t.*(exp(y))-sin(y)),tspan1,1.5);
    
    %% Index of t(3) is ((3/0.05) -1 )
    y_when_t_3 = y1(((3/0.05) -1 ))
    

    Then you can use the function backwards to get values before 2. Like below.

    tspan2 = [ 2 : -0.05 : 0.5];
    [t2,y2]=ode45(@(t,y) -exp(y)./(t.*(exp(y))-sin(y)),tspan2,1.5);
    
    y_when_t_1 = y2(length(tspan2)-((1/0.05) -1 ))
    y_when_t_1_5 = y2(length(tspan2)-((1.5/0.05) -1 ))
    

    Now you have values of t(1), t(1.5) and t(3). What's left is to plot. You can use below code to plot

    t1 = t1';
    t2 = t2';
    y1 = y1';
    y2 = y2';
    
    t_plot = [fliplr(t2),t1(2:end)];
    y_plit = [fliplr(y2),y1(2:end)];
    
    plot(t_plot,y_plot);
    xlabel("t");
    ylabel("y");