Example

This example introduces us to the world of MATLAB/octave when dealing with functions (and "handles"):

% % Solution to simple natural differential equation;% That is: dy(t)/dt + (tau)*y(t) = 0

%

%

tau = 3;

%

t = linspace(0,20,20);

a = exp(-t/tau);

hold off

plot(t,a,'-or')

%

% Solving the simple differential equation using ode45

%

span = [0 20];

y0 = [1];

%

% Use ode45 for MatLab, however lsode should be used for octave

% Use the following two lines for octave and remove the ode45:

% tt = linspace(0,20,100);

% y=lsode('homegoct',y0,tt); % note homegoct has the input parameters reversed

% [tt,y]=ode45(@homeg,span,y0); % alternative MATLAB way

diffopt = odeset("RelTol",1e-5,"AbsTol",1e-5,"NormControl","on");

[tt,y]=ode45(@homeg,span,y0,diffopt);

hold on

plot(tt,y,'-+g')

%

% 1 sec steps between 0 and 20 seconds

%

% Solving the simple differential equation using "diffeqnat" which

% uses a non-corrector Euler method

% (snip) -- CUT OUT BECAUSE THIS IS HOMEWORK %

To do this example you will need the function homeg.m (or homegoct.m which is the same as homeg.m with the input variable reversed):

function nat = homeg(t,x)%

% This is set-up based of MATLAB rules for

% solutions of differential equations.

% Those rules are that all differential function must be

% in the form of dy/dt = f(t,y(t)). It is also possible to

% have a matrix form in front of dy/dt so that we have

% M(t,y) dy/dt = f(t,y(t)); this matrix is called a mass matrix.

Syntax must

% be followed exactly.

% M(t,y) = 1

% f(t,y) = -x_n(t)/tau

%

tau = 3;

%

% nat is natural differential equation (view it as dx/dt)

%

% view x(1) as x_1 not as one value...this can be a little confusing

%

nat = -x(1)/tau;

end