Advanced Exercises
These exercises are harder than the first set and draw on the whole course: classes, file I/O, regular expressions, recursion, sparse matrices, optimization, Fourier analysis and ODEs. Each one has a starter that runs as-is and prints placeholder results, so you can see the expected format. Replace the TODO parts, compare with the "Expected" lines, and only then open the solution (which is runnable too).
| # | Exercise | Topics |
|---|---|---|
| 1 | Bank account | handle classes, validation, errors |
| 2 | 2-D vectors | value classes, operator overloading |
| 3 | Log file summary | fopen/fprintf/fgetl, strsplit, containers.Map |
| 4 | Parsing with regexp | named tokens, struct arrays |
| 5 | Run-length encoding | vectorization, diff, find |
| 6 | Flatten a nested cell | recursion, iscell |
| 7 | Game of Life | conv2, logical arrays |
| 8 | Heat in a rod | sparse matrices, spdiags, backslash |
| 9 | Fit a decay model | fminsearch, anonymous functions |
| 10 | Hidden frequencies | fft, spectra |
| 11 | Epidemic model | ode45, systems of ODEs |
| 12 | Robust input parsing | error identifiers, try/catch |
1. Bank account
Write a handle class Account with a Balance property (starting at 0), and methods deposit(acc, amount) and withdraw(acc, amount). Both must reject non-positive amounts with the error identifier Account:badAmount, and withdraw must refuse to overdraw with Account:insufficient.
Expected:
balance 70.00
Account:insufficient: cannot withdraw 100.00, balance is 70.00
Account:badAmount: amount must be positiveacc = Account();
deposit(acc, 100);
withdraw(acc, 30);
fprintf('balance %.2f\n', acc.Balance);
try, withdraw(acc, 100), catch err, fprintf('%s: %s\n', err.identifier, err.message), end
try, deposit(acc, -5), catch err, fprintf('%s: %s\n', err.identifier, err.message), end
% --- file: Account.m
classdef Account < handle
properties
Balance = 0
end
methods
function deposit(acc, amount)
% TODO: check the amount, then add it
end
function withdraw(acc, amount)
% TODO: check the amount and the balance, then subtract it
end
end
endbalance 0.00
Show solution
acc = Account();
deposit(acc, 100);
withdraw(acc, 30);
fprintf('balance %.2f\n', acc.Balance);
try, withdraw(acc, 100), catch err, fprintf('%s: %s\n', err.identifier, err.message), end
try, deposit(acc, -5), catch err, fprintf('%s: %s\n', err.identifier, err.message), end
% --- file: Account.m
classdef Account < handle
properties
Balance = 0
end
methods
function deposit(acc, amount)
Account.checkAmount(amount);
acc.Balance = acc.Balance + amount;
end
function withdraw(acc, amount)
Account.checkAmount(amount);
if amount > acc.Balance
error('Account:insufficient', 'cannot withdraw %.2f, balance is %.2f', ...
amount, acc.Balance);
end
acc.Balance = acc.Balance - amount;
end
end
methods (Static, Access = private)
function checkAmount(amount)
if ~isnumeric(amount) || ~isscalar(amount) || amount <= 0
error('Account:badAmount', 'amount must be positive');
end
end
end
endbalance 70.00
Account:insufficient: cannot withdraw 100.00, balance is 70.00
Account:badAmount: amount must be positive
Because Account is a handle class, deposit(acc, 100) changes the object itself; no acc = ... assignment is needed. A static private method keeps the shared check in one place.
2. 2-D vectors
Write a value class Vec2 with properties x and y, and overload plus (a + b), mtimes (scalar times vector, in either order), norm and disp (printing (x, y)).
Expected:
(4, 1)
(2, 4)
(-3, 1.5)
norm of b: 3.1623a = Vec2(1, 2); b = Vec2(3, -1);
disp(a + b)
disp(2 * a)
disp(b * -0.5 + Vec2(-1.5, 1))
fprintf('norm of b: %.4f\n', norm(b));
% --- file: Vec2.m
classdef Vec2
properties
x = 0
y = 0
end
methods
function v = Vec2(x, y)
if nargin > 0, v.x = x; v.y = y; end
end
function r = plus(a, b)
r = a; % TODO
end
function r = mtimes(p, q)
r = Vec2(); % TODO: one of p, q is a number
end
function n = norm(v)
n = 0; % TODO
end
function disp(v)
fprintf('(%g, %g)\n', v.x, v.y);
end
end
end(1, 2)
(0, 0)
(0, 0)
norm of b: 0.0000
Show solution
a = Vec2(1, 2); b = Vec2(3, -1);
disp(a + b)
disp(2 * a)
disp(b * -0.5 + Vec2(-1.5, 1))
fprintf('norm of b: %.4f\n', norm(b));
% --- file: Vec2.m
classdef Vec2
properties
x = 0
y = 0
end
methods
function v = Vec2(x, y)
if nargin > 0, v.x = x; v.y = y; end
end
function r = plus(a, b)
r = Vec2(a.x + b.x, a.y + b.y);
end
function r = mtimes(p, q)
if isnumeric(p)
k = p; v = q; % 2 * v
else
k = q; v = p; % v * 2
end
r = Vec2(k * v.x, k * v.y);
end
function n = norm(v)
n = hypot(v.x, v.y);
end
function disp(v)
fprintf('(%g, %g)\n', v.x, v.y);
end
end
end(4, 1)
(2, 4)
(-3, 1.5)
norm of b: 3.1623
MATLAB calls the mtimes of whichever operand is a Vec2, with the operands in their written order, so the method has to check which one is the number.
3. Log file summary
The script writes a small log file. Read it back line by line with fgetl, count the lines per level (INFO, WARN, ERROR) using a containers.Map, and collect the messages of the ERROR lines.
Expected:
ERROR: 2
INFO: 4
WARN: 1
errors: disk full | retry failedfid = fopen('app.log', 'w');
fprintf(fid, '%s\n', '08:00 INFO start', '08:01 INFO user login', '08:05 WARN slow query', ...
'08:07 ERROR disk full', '08:08 INFO cleanup', '08:09 ERROR retry failed', '08:10 INFO stop');
fclose(fid);
counts = containers.Map();
errors = {};
fid = fopen('app.log', 'r');
% TODO: loop with fgetl until it returns -1 (not a char), split each line
fclose(fid);
lv = keys(counts);
for k = 1:numel(lv)
fprintf('%s: %d\n', lv{k}, counts(lv{k}));
end
fprintf('errors: %s\n', strjoin(errors, ' | '));errors:
Show solution
fid = fopen('app.log', 'w');
fprintf(fid, '%s\n', '08:00 INFO start', '08:01 INFO user login', '08:05 WARN slow query', ...
'08:07 ERROR disk full', '08:08 INFO cleanup', '08:09 ERROR retry failed', '08:10 INFO stop');
fclose(fid);
counts = containers.Map();
errors = {};
fid = fopen('app.log', 'r');
line = fgetl(fid);
while ischar(line)
parts = strsplit(line, ' ');
level = parts{2};
if isKey(counts, level)
counts(level) = counts(level) + 1;
else
counts(level) = 1;
end
if strcmp(level, 'ERROR')
errors{end + 1} = strjoin(parts(3:end), ' ');
end
line = fgetl(fid);
end
fclose(fid);
lv = keys(counts);
for k = 1:numel(lv)
fprintf('%s: %d\n', lv{k}, counts(lv{k}));
end
fprintf('errors: %s\n', strjoin(errors, ' | '));ERROR: 2
INFO: 4
WARN: 1
errors: disk full | retry failed
fgetl returns the number -1 at the end of the file, so ischar(line) is the loop condition. keys returns the keys sorted, which is why ERROR comes first.
4. Parsing with regexp
Each line of orders has an order number, a quantity and a product code like AB-123, in varying layouts. Use one regexp call with named tokens to build a struct array with fields id, qty and code, then print the total quantity per order.
Expected:
#1041: 3 x KX-200
#1042: 12 x AB-007
#1043: 1 x QQ-950
total quantity: 16orders = {'order #1041 qty=3 item KX-200', ...
'item AB-007, order #1042, qty=12', ...
'qty=1 order #1043 (QQ-950)'};
pattern = ''; % TODO: (?<id>...), (?<qty>...), (?<code>...)
total = 0;
for k = 1:numel(orders)
% TODO: parse orders{k}, print it and add the quantity
end
fprintf('total quantity: %d\n', total);total quantity: 0
Show solution
orders = {'order #1041 qty=3 item KX-200', ...
'item AB-007, order #1042, qty=12', ...
'qty=1 order #1043 (QQ-950)'};
total = 0;
for k = 1:numel(orders)
id = regexp(orders{k}, '#(?<id>\d+)', 'names');
qty = regexp(orders{k}, 'qty=(?<qty>\d+)', 'names');
code = regexp(orders{k}, '(?<code>[A-Z]{2}-\d{3})', 'names');
rec(k) = struct('id', id.id, 'qty', str2double(qty.qty), 'code', code.code);
fprintf('#%s: %d x %s\n', rec(k).id, rec(k).qty, rec(k).code);
end
fprintf('total quantity: %d\n', sum([rec.qty]));#1041: 3 x KX-200
#1042: 12 x AB-007
#1043: 1 x QQ-950
total quantity: 16
Because the fields appear in a different order on each line, one pattern per field is simpler and more robust than one pattern for the whole line. 'names' returns a struct whose fields are the token names. See Regular Expressions.
5. Run-length encoding
Compress a char array by replacing each run of repeated characters with the character and its count: 'aaabccdddd' becomes 'a3b1c2d4'. Do it without a loop over characters: find where runs start with diff, and get the run lengths from the differences of those positions.
Expected:
a3b1c2d4
W4B1W3B2disp(rle('aaabccdddd'))
disp(rle('WWWWBWWWBB'))
function out = rle(s)
out = s; % TODO
endaaabccdddd
WWWWBWWWBB
Show solution
disp(rle('aaabccdddd'))
disp(rle('WWWWBWWWBB'))
function out = rle(s)
starts = [1, find(diff(double(s)) ~= 0) + 1]; % first index of every run
lengths = diff([starts, numel(s) + 1]);
parts = [num2cell(s(starts)); num2cell(lengths)];
out = sprintf('%c%d', parts{:});
enda3b1c2d4
W4B1W3B2
diff(double(s)) ~= 0 is true where the character changes. Interleaving characters and counts in a 2-row cell array lets one sprintf call build the result.
6. Flatten a nested cell
Write a recursive function flatten(c) that turns a cell array with any depth of nesting into a flat row vector of numbers.
Expected:
1 2 3 4 5 6 7
depth-5 nesting: 42fprintf('%d ', flatten({1, {2, 3}, {{4}, 5, {6, {7}}}})); fprintf('\n');
fprintf('depth-5 nesting: %d\n', flatten({{{{{42}}}}}));
function v = flatten(c)
v = []; % TODO: recurse into elements that are cells
end
depth-5 nesting:
Show solution
fprintf('%d ', flatten({1, {2, 3}, {{4}, 5, {6, {7}}}})); fprintf('\n');
fprintf('depth-5 nesting: %d\n', flatten({{{{{42}}}}}));
function v = flatten(c)
v = [];
for k = 1:numel(c)
if iscell(c{k})
v = [v, flatten(c{k})]; % recursive case
else
v = [v, c{k}(:)']; % base case: numbers
end
end
end1 2 3 4 5 6 7
depth-5 nesting: 42
The base case (a non-cell element) stops the recursion; every cell element is handled by the same function one level deeper. See Recursion.
7. Game of Life
In Conway's Game of Life, a live cell survives if it has 2 or 3 live neighbours, and a dead cell becomes alive if it has exactly 3. Count the neighbours of every cell at once with conv2 and a 3x3 kernel, then advance a glider 4 generations. A glider moves one cell diagonally every 4 generations.
Expected:
generation 0: generation 4:
.#...... ........
..#..... ..#.....
###..... ...#....
........ .###....
........ ........
live cells: 5 -> 5G = false(5, 8);
G(1, 2) = true; G(2, 3) = true; G(3, 1:3) = true;
start = G;
for gen = 1:4
% TODO: n = number of live neighbours of each cell; apply the rules
end
show = @(A) char('.' + A * ('#' - '.'));
fprintf('generation 0: generation 4:\n');
disp([show(start), repmat(' ', 5, 10), show(G)])
fprintf('live cells: %d -> %d\n', nnz(start), nnz(G));generation 0: generation 4:
.#...... .#......
..#..... ..#.....
###..... ###.....
........ ........
........ ........
live cells: 5 -> 5
Show solution
G = false(5, 8);
G(1, 2) = true; G(2, 3) = true; G(3, 1:3) = true;
start = G;
kernel = [1 1 1; 1 0 1; 1 1 1]; % the 8 neighbours, not the cell itself
for gen = 1:4
n = conv2(double(G), kernel, 'same');
G = (G & (n == 2 | n == 3)) | (~G & n == 3);
end
show = @(A) char('.' + A * ('#' - '.'));
fprintf('generation 0: generation 4:\n');
disp([show(start), repmat(' ', 5, 10), show(G)])
fprintf('live cells: %d -> %d\n', nnz(start), nnz(G));generation 0: generation 4:
.#...... ........
..#..... ..#.....
###..... ...#....
........ .###....
........ ........
live cells: 5 -> 5
conv2 with 'same' treats cells outside the board as dead. The update is one logical expression for the whole board, no loop over cells. Compare the kernel idea with Image Processing Basics.
8. Heat in a rod
The steady temperature u(x) of a rod heated along its length, with both ends held at 0, satisfies -u'' = 1 on [0, 1]. With n interior grid points and spacing h = 1/(n+1), the finite-difference equations are a tridiagonal system A u = h^2 * ones(n, 1) with 2 on the diagonal and -1 next to it. Build A as a sparse matrix with spdiags, solve it with backslash, and compare the centre temperature with the exact solution u(x) = x(1 - x)/2.
Expected:
n = 999: 2995 nonzeros out of 998001 entries
u(0.5) = 0.125000 (exact 0.125000)
max error below 1e-10: 1n = 999;
h = 1 / (n + 1);
x = (1:n)' * h;
A = speye(n); % TODO: the tridiagonal matrix
u = zeros(n, 1); % TODO: solve
fprintf('n = %d: %d nonzeros out of %d entries\n', n, nnz(A), numel(A));
mid = round(n / 2);
fprintf('u(%.1f) = %.6f (exact %.6f)\n', x(mid), u(mid), x(mid) * (1 - x(mid)) / 2);
fprintf('max error below 1e-10: %d\n', max(abs(u - x .* (1 - x) / 2)) < 1e-10);n = 999: 999 nonzeros out of 998001 entries
u(0.5) = 0.000000 (exact 0.125000)
max error below 1e-10: 0
Show solution
n = 999;
h = 1 / (n + 1);
x = (1:n)' * h;
e = ones(n, 1);
A = spdiags([-e 2*e -e], -1:1, n, n);
u = A \ (h^2 * e);
fprintf('n = %d: %d nonzeros out of %d entries\n', n, nnz(A), numel(A));
mid = round(n / 2);
fprintf('u(%.1f) = %.6f (exact %.6f)\n', x(mid), u(mid), x(mid) * (1 - x(mid)) / 2);
fprintf('max error below 1e-10: %d\n', max(abs(u - x .* (1 - x) / 2)) < 1e-10);n = 999: 2995 nonzeros out of 998001 entries
u(0.5) = 0.125000 (exact 0.125000)
max error below 1e-10: 1
For a quadratic solution the central difference is exact, so the only error is rounding. A full 999x999 matrix would store a million numbers; the sparse one stores about three thousand. See Sparse Matrices.
9. Fit a decay model
A sensor's signal decays like y = A exp(-k t). Find A and k by minimising the sum of squared errors with fminsearch, starting from [1 1]. Print the results rounded to 3 decimals.
Expected:
A = 5.029, k = 0.404
SSE = 0.0010t = 0:1:8;
y = [5.02 3.38 2.24 1.48 1.01 0.66 0.45 0.30 0.20];
model = @(p, t) p(1) * exp(-p(2) * t);
sse = @(p) 0; % TODO: sum of squared errors of model(p, t)
p = [1 1]; % TODO: minimise sse
fprintf('A = %.3f, k = %.3f\n', p);
fprintf('SSE = %.4f\n', sse(p));A = 1.000, k = 1.000
SSE = 0.0000
Show solution
t = 0:1:8;
y = [5.02 3.38 2.24 1.48 1.01 0.66 0.45 0.30 0.20];
model = @(p, t) p(1) * exp(-p(2) * t);
sse = @(p) sum((y - model(p, t)).^2);
opts = optimset('TolX', 1e-10, 'TolFun', 1e-12, 'MaxFunEvals', 5000, 'MaxIter', 5000);
p = fminsearch(sse, [1 1], opts);
fprintf('A = %.3f, k = %.3f\n', p);
fprintf('SSE = %.4f\n', sse(p));A = 5.029, k = 0.404
SSE = 0.0010
Tight tolerances make the result reproducible to the printed digits in MATLAB and Octave. A quick alternative is a straight-line fit of log(y) against t with polyfit, which weights the errors differently and gives slightly different values. See Optimization and Curve Fitting.
10. Hidden frequencies
The signal below is sampled at 200 Hz for 1 second and contains two sine waves. Use fft to compute the one-sided amplitude spectrum and report the two strongest frequencies with their amplitudes.
Expected:
peak at 12 Hz, amplitude 1.50
peak at 45 Hz, amplitude 0.60fs = 200; t = (0:fs-1) / fs;
x = 1.5 * sin(2*pi*12*t) + 0.6 * cos(2*pi*45*t) + 0.2;
N = numel(x);
f = (0:N/2) * fs / N; % frequencies of the one-sided spectrum
amp = zeros(size(f)); % TODO: amplitudes from fft(x)
[~, idx] = sort(amp, 'descend');
for k = idx(1:2)
fprintf('peak at %g Hz, amplitude %.2f\n', f(k), amp(k));
endpeak at 0 Hz, amplitude 0.00
peak at 1 Hz, amplitude 0.00
Show solution
fs = 200; t = (0:fs-1) / fs;
x = 1.5 * sin(2*pi*12*t) + 0.6 * cos(2*pi*45*t) + 0.2;
N = numel(x);
f = (0:N/2) * fs / N;
X = fft(x);
amp = abs(X(1:N/2 + 1)) / N;
amp(2:end-1) = 2 * amp(2:end-1); % fold the negative frequencies in
amp(1) = 0; % ignore the constant offset (0 Hz)
[~, idx] = sort(amp, 'descend');
for k = idx(1:2)
fprintf('peak at %g Hz, amplitude %.2f\n', f(k), amp(k));
endpeak at 12 Hz, amplitude 1.50
peak at 45 Hz, amplitude 0.60
With exactly one second of data the frequency resolution is 1 Hz, so both tones fall exactly on a frequency bin. The 0 Hz bin holds the mean (0.2) and is excluded. See Fourier Transform & Signals.
11. Epidemic model
The SIR model splits a population into susceptible S, infected I and recovered R fractions:
S' = -b S I, I' = b S I - g I, R' = g I. With b = 0.3, g = 0.1, S(0) = 0.99, I(0) = 0.01, R(0) = 0, solve it over 160 days with ode45 (output every 0.1 day), and report the peak of I, the day it happens, and the final recovered fraction.
Expected:
peak infected: 0.304 on day 26.6
recovered after 160 days: 0.941b = 0.3; g = 0.1;
rhs = @(t, y) [0; 0; 0]; % TODO: the three equations, y = [S; I; R]
[t, y] = ode45(rhs, 0:0.1:160, [0.99; 0.01; 0]);
[peak, k] = max(y(:, 2));
fprintf('peak infected: %.3f on day %.1f\n', peak, t(k));
fprintf('recovered after 160 days: %.3f\n', y(end, 3));peak infected: 0.010 on day 49.1
recovered after 160 days: 0.000
Show solution
b = 0.3; g = 0.1;
rhs = @(t, y) [-b * y(1) * y(2);
b * y(1) * y(2) - g * y(2);
g * y(2)];
opts = odeset('RelTol', 1e-9, 'AbsTol', 1e-12);
[t, y] = ode45(rhs, 0:0.1:160, [0.99; 0.01; 0], opts);
[peak, k] = max(y(:, 2));
fprintf('peak infected: %.3f on day %.1f\n', peak, t(k));
fprintf('recovered after 160 days: %.3f\n', y(end, 3));
fprintf('S + I + R stays 1: %d\n', all(abs(sum(y, 2) - 1) < 1e-8));peak infected: 0.304 on day 26.6
recovered after 160 days: 0.941
S + I + R stays 1: 1
The three derivatives add up to zero, so S + I + R is conserved, a good sanity check for any ODE model. See Systems of ODEs.
12. Robust input parsing
Write c = parse_temp(txt) that converts texts like '21.5C', '70F' or ' -3 c ' to degrees Celsius. Throw parse_temp:format for text that doesn't match a number followed by C or F, and parse_temp:range for results below absolute zero (-273.15 C). The caller prints a message per input.
Expected:
'21.5C' -> 21.50 C
'70F' -> 21.11 C
' -3 c ' -> -3.00 C
'hot' -> parse_temp:format
'-500F' -> parse_temp:rangeinputs = {'21.5C', '70F', ' -3 c ', 'hot', '-500F'};
for k = 1:numel(inputs)
label = sprintf('''%s''', inputs{k});
try
fprintf('%-9s -> %6.2f C\n', label, parse_temp(inputs{k}));
catch err
fprintf('%-9s -> %s\n', label, err.identifier);
end
end
function c = parse_temp(txt)
c = 0; % TODO: regexp, unit conversion, two kinds of errors
end'21.5C' -> 0.00 C
'70F' -> 0.00 C
' -3 c ' -> 0.00 C
'hot' -> 0.00 C
'-500F' -> 0.00 C
Show solution
inputs = {'21.5C', '70F', ' -3 c ', 'hot', '-500F'};
for k = 1:numel(inputs)
label = sprintf('''%s''', inputs{k});
try
fprintf('%-9s -> %6.2f C\n', label, parse_temp(inputs{k}));
catch err
fprintf('%-9s -> %s\n', label, err.identifier);
end
end
function c = parse_temp(txt)
tok = regexp(strtrim(txt), '^([-+]?\d+(\.\d+)?)\s*([CcFf])