skip to primary navigationskip to content
 

practicalTwoCode.m

Objective-C source code icon practicalTwoCode.m — Objective-C source code, 2 KB (2190 bytes)

File contents

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Model answers to exercises in Matlab Practical %
% Nik Cunniffe: Oct 2010                         %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% clear Matlabs memory, shut all plots, etc.
close all;
clear all;

% Exercise One
deltaT = 0.01;
tMax = 3.0;
yZero = 2.0;

vT = [0:deltaT:tMax];
nT = length(vT);
vY = zeros(nT,1);
vY(1) = yZero;
for i=2:nT
   vY(i) = vY(i-1)+deltaT*vT(i-1)*vY(i-1); 
end

plot(vT,vY);

% Exercise Two
% (handwritten)
% the exact answer is y=2exp(t^2/2)

% Exercise Three
% exactSoln in separate file

% below code checks it works
yAtZero = exactSoln(0)
yAtOne = exactSoln(1)
yAtZeroOneTwoThree = exactSoln([0:3])

% Exercise Four
close all;  % clear previous plot
plot(vT,vY);
hold on
plot(vT, exactSoln(vT),'r');
legend('approximation','exact solution');
xlabel('t');
ylabel('y');
title('Euler''s method approximation');

% Exercise Five
% in separate file
% checks below

myRHS(2,3)
myRHS([0:2],[3:5])

% Exercise Six

clear all;
close all;
tRange = [0,2];			% set up range for t
yZero = 2;				% and an initial condition
[myT,myY]=ode45(@myRHS,tRange,yZero);	% solve
plot(myT,myY,'c');
hold on
plot(myT, exactSoln(myT),'ro');
legend('approximation','exact solution');
xlabel('t');
ylabel('y');
title('Runge-Kutta method approximation');

% Preamble to Exercise 7

options=odeset('RelTol',1e-10);
tRange = [0:1];		% set up range for t
yZero = 1;				% and an initial condition
[myT,myY]=ode45(@myRHS,tRange,yZero,options);	% solve

tRange = [0,100];			% set up range for t
yZero(1) = 0.2;			% and an initial condition
yZero(2) = 0.1;;
[myT,myY]=ode45(@lvRHS,tRange,yZero);	% solve
plot(myT,myY(:,1),'c');
hold on
plot(myT,myY(:,2));
legend('prey','predator')

% exercise Eight
close all;
clear all;
%tRange = [0:0.00001:0.1];			% set up range for t
tRange = [0:0.001:20.0];			% set up range for t
yZero(1) = 5;			% and an initial condition
yZero(2) = 0.0;
[myT,myY]=ode45(@mmRHS,tRange,yZero);	% solve
plot(myT,myY(:,1));
xlabel('t');
ylabel('S');
figure;
plot(myT,myY(:,2));
xlabel('t');
ylabel('C');