Practice Exercises

Concept

Exercises graded by level. Try them yourself first; worked solutions for a selection follow.

Temperature conversion table · Prime numbers (sieve) · Palindromes · Mean/median/std of a dataset · FizzBuzz · Area and perimeter functions · Grade calculator · Multiplication table

Column statistics of a measurement matrix · Log parsing and counting by level · Bank account with a struct · Run-length encoding · Word frequency with containers.Map · CSV report generator · Plot of a sensor signal with limits

Newton's method for a nonlinear system · 1-D heat diffusion by finite differences · Monte Carlo estimation · Scalar Kalman filter · ODE simulation of a mass-spring-damper · FFT-based vibration analysis · PI controller simulation

Full CAN log analyzer (decode, statistics, plots) · Battery SoC estimator with an extended Kalman filter · Optimize a controller's gains with fminsearch against a cost function · Class-based test framework for a Simulink model · Vectorized image filtering

Why It Matters

Fluency comes from solving problems, not from reading about them.

Syntax

Run each solution as a script in the same folder as the helper function files from Module 11.

Example

34.1 Beginner solutions 34.2 Intermediate solutions 34.3 Advanced solutions

% Beginner exercises: temperature table, primes, palindrome, statistics, FizzBuzz
c = -20:20:100;
fprintf('%6s %8s\n', 'C', 'F');
fprintf('%6d %8.1f\n', [c; celsius_to_fahrenheit(c)]);

n = 50;
isP = true(1, n); isP(1) = false;               % sieve of Eratosthenes
for k = 2:floor(sqrt(n))
    if isP(k), isP(k * k:k:n) = false; end
end
fprintf('primes up to 50: %s (matches primes(50): %d)\n', mat2str(find(isP)), isequal(find(isP), primes(50)))

words = {'level', 'Never odd or even', 'matlab'};
for k = 1:numel(words)
    s = lower(words{k}(isletter(words{k})));
    fprintf('"%s" palindrome: %d\n', words{k}, strcmp(s, fliplr(s)))
end

x = [4 8 15 16 23 42];
fprintf('mean %.2f, median %.1f, std %.3f, range %d\n', mean(x), median(x), std(x), max(x) - min(x))

out = cell(1, 15);
for k = 1:15
    if mod(k, 15) == 0, out{k} = 'FizzBuzz';
    elseif mod(k, 3) == 0, out{k} = 'Fizz';
    elseif mod(k, 5) == 0, out{k} = 'Buzz';
    else, out{k} = num2str(k);
    end
end
fprintf('%s\n', strjoin(out, ' '))
% Intermediate exercises: matrix statistics per column, log parsing, bank account struct, run-length encoding
M = [12.6 25 5.1; 12.4 27 5.3; 12.9 26 4.9; 12.2 31 5.6];
names = {'voltage', 'temperature', 'current'};
for c = 1:3
    fprintf('%-11s mean %6.2f  min %6.2f  max %6.2f\n', names{c}, mean(M(:, c)), min(M(:, c)), max(M(:, c)))
end

entries = {'08:00:01 INFO flash start', '08:00:09 WARN low voltage', '08:01:15 ERROR timeout', '08:03:30 ERROR timeout'};
levels = cellfun(@(s) strtok(s(10:end)), entries, 'UniformOutput', false);
[u, ~, idx] = unique(levels);
cnt = accumarray(idx(:), 1);
for k = 1:numel(u), fprintf('%-5s %d\n', u{k}, cnt(k)); end

acct = struct('owner', 'Asha', 'balance', 500, 'history', {{}});
ops = [-120.5 200 -1000];
for op = ops
    if acct.balance + op < 0
        acct.history{end + 1} = sprintf('rejected %.2f', op);
    else
        acct.balance = acct.balance + op;
        acct.history{end + 1} = sprintf('%+.2f', op);
    end
end
fprintf('%s: balance %.2f; history: %s\n', acct.owner, acct.balance, strjoin(acct.history, ', '))

x = [1 1 1 0 0 1 1 1 1 0];
starts = [1 find(diff(x) ~= 0) + 1];
lens = diff([starts numel(x) + 1]);
fprintf('run-length encoding: v
…
% Advanced exercises: Newton-Raphson for a system, 2-D heat diffusion, Monte Carlo pi, Kalman-style filter
% 1. Newton's method for two nonlinear equations: x^2 + y^2 = 4, x*y = 1
F = @(p) [p(1)^2 + p(2)^2 - 4; p(1) * p(2) - 1];
J = @(p) [2 * p(1), 2 * p(2); p(2), p(1)];
p = [2; 0.5];
for k = 1:6, p = p - J(p) \ F(p); end
fprintf('Newton system: x = %.8f, y = %.8f, residual %.1e\n', p, norm(F(p)))

% 2. explicit finite differences: temperature of a rod, fixed ends at 100 and 0
n = 11; alpha = 0.25; T = zeros(1, n); T(1) = 100;
for step = 1:2000
    T(2:end - 1) = T(2:end - 1) + alpha * (T(1:end - 2) - 2 * T(2:end - 1) + T(3:end));
end
fprintf('steady-state rod temperatures: %s (linear from 100 to 0)\n', mat2str(round(T)))

% 3. Monte Carlo estimate of pi
rng(11);
N = 1e6;
pts = rand(N, 2);
est = 4 * mean(sum(pts .^ 2, 2) <= 1);
fprintf('Monte Carlo pi with %d points: %.4f (error %.4f)\n', N, est, abs(est - pi))

% 4. scalar Kalman filter smoothing a noisy constant voltage
rng(5);
truth = 12.6; z = truth + 0.3 * randn(1, 200);
xk = z(1); Pk = 1; Q = 1e-5; R = 0.09;
for k = 2:numel(z)
    Pk = Pk + Q;
    K = Pk / (Pk + R);
    xk = xk + K * (z(k) - xk);
    Pk = (1 - K) * Pk;
end
fp
…

Expected Result

The hand-written sieve matches primes(50).

The bank account rejected the withdrawal that would have overdrawn it.

Newton's method solved the 2×2 nonlinear system to full precision.

The explicit finite-difference scheme converged to the linear steady-state profile (it is stable because α ≤ 0.5).

The Kalman filter estimate is much closer to the true 12.6 V than individual noisy samples.

(Random-number-based results differ in MATLAB.)

C        F
   -20     -4.0
     0     32.0
    20     68.0
    40    104.0
    60    140.0
    80    176.0
   100    212.0
primes up to 50: [2 3 5 7 11 13 17 19 23 29 31 37 41 43 47] (matches primes(50): 1)
"level" palindrome: 1
"Never odd or even" palindrome: 1
"matlab" palindrome: 0
mean 18.00, median 15.5, std 13.491, range 38
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
voltage     mean  12.53  min  12.20  max  12.90
temperature mean  27.25  min  25.00  max  31.00
current     mean   5.22  min   4.90  max   5.60
ERROR 2
INFO  1
WARN  1
Asha: balance 579.50; history: -120.50, +200.00, rejected -1000.00
run-length encoding: values [1 0 1 0], lengths [3 2 4 1]
Newton system: x = 1.93185165, y = 0.51763809, residual 1.1e-16
steady-state rod temperatures: [100 90 80 70 60 50 40 30 20 10 0] (linear from 100 to 0)
Monte Carlo pi with 1000000 points: 3.1421 (error 0.0005)
Kalman estimate 12.6025 V (truth 12.6), raw sample std 0.300

Common Mistakes

Starting with the hardest exercise; build up from the beginner set.

Solving only the example inputs; test edge cases (empty input, one element, negative values).

Copying the solutions without running them.

Best Practices

Solve first with loops, then vectorize, then compare speed.

Write assert checks for known results.

Keep your solutions in a personal repository.

Interview Relevance

High: interview coding rounds for MATLAB roles use exactly this kind of problem.

Practice Questions

Solve the remaining exercises in the table.

Vectorize the FizzBuzz solution.

Add a plot to the heat-diffusion solution showing the profile every 200 steps.

Extend the Kalman filter to track a slowly rising voltage (a two-state model).

Quick Quiz

Q1. (Predict the output) The sieve's result for n = 50 matched primes(50)?

Answer: Yes (verified).

Q2. (True/False) The explicit heat-equation scheme with α = 0.25 is stable.

Answer: True (the condition is α ≤ 0.5).

Q3. (Multiple choice) Monte Carlo estimation error typically shrinks proportionally to: A) 1/N B) 1/√N C) 1/N² D) It doesn't shrink Answer: B.

Q4. (Find the bug) A run-length encoder returns lengths that don't sum to the input length.

Answer: The last run's length is missing; append the end position (numel(x) + 1) before taking differences, as in the solution.

Coding Challenge

Write a vectorized FizzBuzz for 1..15 that builds the output without an if inside a loop.

n = 1:15;
out = arrayfun(@num2str, n, 'UniformOutput', false);
out(mod(n, 3) == 0) = {'Fizz'};
out(mod(n, 5) == 0) = {'Buzz'};
out(mod(n, 15) == 0) = {'FizzBuzz'};
fprintf('%s\n', strjoin(out, ' '))