TExcelTAD
Home › MATLAB / Octave › Advanced Exercises

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:

text
balance 70.00
Account:insufficient: cannot withdraw 100.00, balance is 70.00
Account:badAmount: amount must be positive
matlab · try it yourself
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)
            % TODO: check the amount, then add it
        end
        function withdraw(acc, amount)
            % TODO: check the amount and the balance, then subtract it
        end
    end
end
balance 0.00
Show solution
matlab · try it yourself
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
end
balance 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:

text
(4, 1)
(2, 4)
(-3, 1.5)
norm of b: 3.1623
matlab · try it yourself
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 = 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
matlab · try it yourself
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:

text
ERROR: 2
INFO: 4
WARN: 1
errors: disk full | retry failed
matlab · try it yourself
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');
% 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
matlab · try it yourself
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:

text
#1041: 3 x KX-200
#1042: 12 x AB-007
#1043: 1 x QQ-950
total quantity: 16
matlab · try it yourself
orders = {'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
matlab · try it yourself
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:

text
a3b1c2d4
W4B1W3B2
matlab · try it yourself
disp(rle('aaabccdddd'))
disp(rle('WWWWBWWWBB'))

function out = rle(s)
out = s;      % TODO
end
aaabccdddd
WWWWBWWWBB
Show solution
matlab · try it yourself
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{:});
end
a3b1c2d4
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:

text
1 2 3 4 5 6 7
depth-5 nesting: 42
matlab · try it yourself
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 = [];       % TODO: recurse into elements that are cells
end

depth-5 nesting:
Show solution
matlab · try it yourself
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
end
1 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:

text
generation 0:     generation 4:
.#......          ........
..#.....          ..#.....
###.....          ...#....
........          .###....
........          ........
live cells: 5 -> 5
matlab · try it yourself
G = 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
matlab · try it yourself
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:

text
n = 999: 2995 nonzeros out of 998001 entries
u(0.5) = 0.125000 (exact 0.125000)
max error below 1e-10: 1
matlab · try it yourself
n = 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
matlab · try it yourself
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:

text
A = 5.029, k = 0.404
SSE = 0.0010
matlab · try it yourself
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) 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
matlab · try it yourself
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:

text
peak at 12 Hz, amplitude 1.50
peak at 45 Hz, amplitude 0.60
matlab · try it yourself
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;          % 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));
end
peak at 0 Hz, amplitude 0.00
peak at 1 Hz, amplitude 0.00
Show solution
matlab · try it yourself
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));
end
peak 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:

text
peak infected: 0.304 on day 26.6
recovered after 160 days: 0.941
matlab · try it yourself
b = 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
matlab · try it yourself
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:

text
'21.5C'   ->  21.50 C
'70F'     ->  21.11 C
' -3 c '  ->  -3.00 C
'hot'     -> parse_temp:format
'-500F'   -> parse_temp:range
matlab · try it yourself
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)
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
matlab · try it yourself
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])
  

, 'tokens', 'once');
if isempty(tok)
    error('parse_temp:format', 'cannot read a temperature from "%s"', txt);
end
value = str2double(tok{1});
if upper(tok{end}) == 'F'
    c = (value - 32) * 5 / 9;
else
    c = value;
end
if c < -273.15
    error('parse_temp:range', '%.2f C is below absolute zero', c);
end
end
'21.5C'   ->  21.50 C
'70F'     ->  21.11 C
' -3 c '  ->  -3.00 C
'hot'     -> parse_temp:format
'-500F'   -> parse_temp:range

Testing err.identifier instead of the message lets the caller react to each kind of problem, and keeps working if the wording changes. See Error Handling.

Test yourself

Why can deposit(acc, 100) change acc without returning it?

  1. All MATLAB objects are references
  2. Account derives from handle, so methods modify the shared object
  3. deposit is a static method
  4. MATLAB passes every argument by reference

In the Game of Life solution, what does conv2(double(G), [1 1 1; 1 0 1; 1 1 1], 'same') compute?

  1. The next generation
  2. The number of live neighbours of every cell
  3. The number of live cells
  4. The cells that die

What does fgetl return when the end of the file is reached?

  1. An empty char array
  2. The number -1
  3. NaN
  4. It throws an error