ODE: First Order: Numerical Solution

The first order ODE is defined below.

In State space form

MATLAB Code
% Example of a first order system - Numerical solution
% P. Venkataraman
% dht/dt + h/(AR) = Qin(t)/A; h(0) = 40
%
% A = 78.5, R = 100;
% (a) Qin(t) = 0; (natural response)
% (b) Qin(t) = 0.3(step response)
%-----------------------------------
% Natural response and forced response
%--------------------
clear      % clears all variables
clc      % clears window and starts at top
A = 78.5; R = 100;  Qina = 0.3;

h0 = 40;  % initial conditions
tinterval = [0 5000];  % range for integration

% define an inline function object  defining the rhs of
% state space definition
nat_sys = inline('-h/(78.5*100)','t','h');
% numerical solution is obtained using the
% Runge_Kutta 4/5 technique
[t h] = ode45(nat_sys,tinterval,h0);

% obtain the forced response/solution
for_sys = inline('-h/(78.5*100) + 0.3/78.5','t','h');
[ta ha] = ode45(for_sys,tinterval,h0);

format compact
set(gcf,'Menubar','none','Name','First Order ODE - Numerical Calculation', ...
'NumberTitle','off','Position',[10,350,700,300], ...
'Color',[0.5 0.8 0.5]);

%-----------------------------------------
hp(1) = subplot('Position',[0.1 0.15 0.35 0.75]);
plot(t,h,'r','LineWidth',2)
title('\bf\itNatural Motion - No Input','Color','k', ...
'VerticalAlignment','bottom')
ylabel('h(m)', ...
'FontWeight','b','Color','b', ...
'VerticalAlignment','bottom');

xlabel('time(s)', ...
'FontWeight','b','Color','b', ...
'VerticalAlignment','top');  % boldface blue
legend('Natural Motion');
grid

%-----------------------------------------
hp(2) = subplot('Position',[0.55 0.15 0.35 0.75]);
plot(ta,ha,'k--','LineWidth',2)
title('\bf\itForced Motion - Constant Input','Color','k', ...
'VerticalAlignment','bottom')
ylabel('h(m)', ...
'FontWeight','b','Color','b', ...
'VerticalAlignment','bottom');

xlabel('time(s)', ...
'FontWeight','b','Color','b', ...
'VerticalAlignment','top');  % boldface blue
legend('Forced Response');
grid
txtstr = strcat('Inflow Q_{in}(t)[m^3/s] =  ',num2str(Qina));
text(ta(5),min(ha)+1,txtstr);