%% Matlab Tutorial: Solving Ordinary Differential Equations
%% Kurt Bryan and SIMIODE
%
% This is intended as a brief introduction to using Matlab to solve ordinary differential equations (ODEs). The focus is primarily on first-order equations, but there is a second-order example as well.
%
% Example 1: Consider the ordinary differential equation u'(t) = u(t) + t. The dsolve command can be used to find the general solution to this ODE, as

syms u(t); %Declare u(t) as symbolic function
ode = diff(u(t),t) == t + u(t) %Define the ODE
dsolve(ode) %General solution

%
% Example 2:  Let us solve the ODE from Example 1 but with an initial  condition, specifically, u(0) = 2. We already defined "ode" above. The command to solve the ODE is

dsolve(ode,u(0)==2) %Incorporate initial condition

% We can define the solution as a function "usol(t)" with the command

usol(t) = dsolve(ode,u(0)==2) %Define solution as a function "usol(t)"

% To plot the solution on the range t = 0 to t = 5, execute

tt = linspace(0,5,100); %Define t coordinates at which we evaluate usol(t)
plot(tt,usol(tt)) %Plot the points (t,usol(t))

%
% Example 3: Let's solve the second order ODE u''(t) + 3*u'(t) + 2*u(t) = sin(t) with initial conditions u(0) = 1  and u'(0) = 2. Define the ODE as

ode = diff(u(t),t,2) + 3*diff(u(t),t) + 2*u(t) == sin(t)

% and solve with the initial data as

Du = diff(u); %Defines the derivative u't) as a function
usol(t) = dsolve(ode,[u(0)==1 Du(0)==2])

%