# Plotting first-order differential equation with initial condition

120 views (last 30 days)
Erin Manogaran on 21 Jan 2020
Commented: Walter Roberson on 24 Jan 2020
I need to plot the solution curve of the differential equation: y'+ty=t^2 on the matlab program. I was given the intial condition of y(0)=3 and I need to graph it on the interval of [-4,4]. I understand how to find the solution of the differential equation but I don't know how to graph the solution curve.

Show 1 older comment
Erin Manogaran on 21 Jan 2020
I tried ODE45 and got this code:
tspan = [0 5];
y0 = 3;
[t,y] = ode45(@(t,y) t^2-(t*y), tspan, y0);
However I got an inccorect graph. I am not sure what I got wrong.
This is the graph I got:
This is the correct graph:
David Goodmanson on 21 Jan 2020
Hi Erin,
tspan = [0 4];
y0 = 3;
[t,y] = ode45(@(t,y) t^2-(t*y), tspan, y0);
plot(t,y); grid on
The span of t here duplicates the right hand half of your sample plot. Once you use grid on, as you almost always should, you will probably like the comparison. Negative x would be a separate calculation.
Walter Roberson on 24 Jan 2020
Your "correct graph" is a vector field or quiver plot. Each point on a grid needs a direction and a length, or a pair of lengths that together are interpreted as a vector. There is nothing in the code you showed us that provides the information that would be needed for such a plot.

Guru Mohanty on 24 Jan 2020
Hi, I understand you are trying to plot the differential equation. The issue while plotting with ode45 is it tries to solve it numerically. The solver imposes the initial conditions given by y0 at the initial time tspan(1), then integrates from tspan(1) to tspan(end). But in your scenario initial condition is at t = 0 and tspan(1) = -4. If you plot the ODE in the interval [0, 4] the ode45 will give correct result. However, you can plot the solution of differential equation using Symbolic toolbox and dsolve function. You may mention the appropriate range in fplot while plotting the solution. Here is the code for it.
clc;
clear all;
syms y(t)
eqn = diff(y,1)+ t*y ==t^2;
cond = y(0)==3;
sol = dsolve(eqn,cond);
fplot(sol,[-4,4]);
grid on;