Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 45 ยท Practice and Review

Practice Exercises with Solutions

Twenty graded MATLAB and Octave exercises on matrices, loops, functions, plots and numerical methods, with collapsible solutions and Python stand-ins.

Reading about matrices is not the same as being fluent with them. This page gives you twenty exercises, ordered from easy to demanding, covering the whole course: indexing, loops, functions, plots and numerical methods. Try each one on paper or in your own MATLAB or Octave session before you open the solution.

Every exercise has a collapsible solution written in real MATLAB (it also runs in Octave unless noted). Each group of four ends with a runnable Python stand-in that computes the same answers, so you can compare results even though this site cannot run MATLAB itself.

The matlab blocks are read-only. The TryIt editors are Python (NumPy, SciPy, matplotlib) stand-ins. They copy MATLAB's 1-based numbering in their printed messages, but the code itself is ordinary Python, so slices and ranges look different. See MATLAB, Octave and Python Compared for a translation table.

Twenty exercises, five themes

Matrices Slicing, masks and clean-up.
Loops Loops first, then vectorized.
Functions Outputs, handles, recursion.
Plots and numerics Figures, fits, roots, integrals.

Solve first, peek second.

1 / 2

How to use this page

Work in this order for each exercise: read the task, predict the shape and type of the answer, write the code, run it, and only then compare with the solution. If your answer differs, work out why before moving on. Often both are correct, because MATLAB has many ways to say the same thing.

Grades: Easy exercises use one idea from one lesson, Medium ones combine two ideas, and Hard ones need you to plan a small algorithm.

Matrices (exercises 1 to 4)

1. Slice a magic square (Easy)

Let A = magic(4). Extract the 2-by-2 block in the middle, the main diagonal as a row vector, and the sum of each row as a row vector.

Show solution
MATLAB
A = magic(4);
center = A(2:3, 2:3)
d      = diag(A)'
rowSum = sum(A, 2)'      % dimension 2 = across each row

diag returns a column, so the transpose makes it a row. Every row of a magic square adds up to the same value, which is a quick sanity check.

2. Checkerboard (Easy)

Build a 6-by-6 matrix of 0s and 1s in a checkerboard pattern with the top-left element equal to 0. Do not use loops.

Show solution
MATLAB
[i, j] = meshgrid(1:6);
board = mod(i + j, 2)

An element at row i and column j is 1 exactly when i + j is odd. meshgrid(1:6) gives two 6-by-6 matrices holding the column numbers and the row numbers, so one mod call fills the whole board.

3. Drop the bad rows (Medium)

Given a matrix M with five rows, delete every row that contains at least one negative number. Use M = [4 7 1; -2 5 9; 3 3 3; 8 -1 6; 0 2 5].

Show solution
MATLAB
M = [4 7 1; -2 5 9; 3 3 3; 8 -1 6; 0 2 5];
bad = any(M < 0, 2);     % one flag per row
M(bad, :) = [];          % delete those rows
M

M < 0 is a mask the size of M. any(..., 2) collapses each row to one flag. Assigning [] through a row index deletes whole rows, leaving rows 1, 3 and 5.

4. Fill gaps with column means (Medium)

For X = [1 NaN 3; 4 5 NaN; 7 8 9], replace each NaN with the mean of the valid values in its own column.

Show solution
MATLAB
X = [1 NaN 3; 4 5 NaN; 7 8 9];
cm = mean(X, 'omitnan');     % older Octave: use nanmean from the statistics package
[r, c] = find(isnan(X));
X(isnan(X)) = cm(c)

find lists the NaN positions column by column, which is the same order that X(isnan(X)) uses, so cm(c) lines up with the elements being replaced. The mask therefore selects the gaps, and cm(c) supplies one matching column mean for each.

Python Stand-ins for exercises 1 to 4

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Loops and vectorizing (exercises 5 to 8)

5. Collatz steps (Easy)

Start with n = 27. While n is not 1, halve it if it is even, otherwise replace it with 3n + 1. Count the steps.

Show solution
MATLAB
n = 27;
steps = 0;
while n ~= 1
    if mod(n, 2) == 0
        n = n / 2;
    else
        n = 3 * n + 1;
    end
    steps = steps + 1;
end
steps      % 111

A while loop fits because you do not know the number of iterations in advance. The sequence for 27 climbs above 9000 before it falls to 1.

6. Sieve of Eratosthenes (Hard)

Find all primes up to 50 with a sieve: keep a logical array, and for each prime k up to sqrt(50) cross out its multiples starting at k*k. Compare the answer with the built-in primes(50).

Show solution
MATLAB
N = 50;
isp = true(1, N);
isp(1) = false;
for k = 2:floor(sqrt(N))
    if isp(k)
        isp(k*k:k:N) = false;     % cross out multiples in one statement
    end
end
mine = find(isp)
isequal(mine, primes(N))          % 1
numel(mine)                       % 25

The inner loop of the classic algorithm became one vectorized assignment with a stepped range. Only the outer loop remains, and it runs just six times.

7. Running maximum (Medium)

For v = [3 1 4 1 5 9 2 6 5 3], build a vector whose k-th element is the largest value among v(1:k). Solve it with a loop first, then with one built-in call.

Show solution
MATLAB
v = [3 1 4 1 5 9 2 6 5 3];
out = zeros(size(v));           % preallocate
cur = v(1);
for k = 1:numel(v)
    cur = max(cur, v(k));
    out(k) = cur;
end
out
cummax(v)                        % same result in one call

Preallocating out avoids growing the array inside the loop. cummax is the vectorized version and is preferable for speed and clarity.

8. Sum of odd squares (Easy)

Compute 1 squared plus 3 squared plus 5 squared, and so on up to 99 squared, without a loop. Then confirm the result with a loop.

Show solution
MATLAB
s = sum((1:2:99).^2)     % 166650

total = 0;
for q = 1:2:99
    total = total + q^2;
end
total == s

The dot in .^ squares each element separately. Without it, ^ would try a matrix power and fail because a row vector is not square.

Python Stand-ins for exercises 5 to 8

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Functions (exercises 9 to 12)

9. Several outputs (Easy)

Write a function stats3 that takes a vector and returns its minimum, maximum and mean as three separate outputs. Call it on [4 8 15 16 23 42].

Show solution
MATLAB
% stats3.m
function [mn, mx, av] = stats3(v)
    mn = min(v);
    mx = max(v);
    av = mean(v);
end
MATLAB
[lo, hi, avg] = stats3([4 8 15 16 23 42])

The file name must match the function name. Outputs you do not request (for example lo = stats3(v)) are simply not returned. See Scripts and Functions.

10. Handles and cellfun (Medium)

Given words = {'matrix', 'vector', 'scalar', 'tensor', 'a'}, compute the length of each word, then keep only the words longer than five characters.

Show solution
MATLAB
words = {'matrix', 'vector', 'scalar', 'tensor', 'a'};
lengths = cellfun(@numel, words)      % 6 6 6 6 1
longWords = words(lengths > 5)

@numel is a function handle. cellfun applies it to each cell and, because every result is one number, gathers them in a numeric array. Indexing a cell array with parentheses returns another cell array, which is what we want here.

11. Recursive gcd (Medium)

Write a recursive function mygcd(a, b) using Euclid's rule: the gcd of a and 0 is a, otherwise it is the gcd of b and mod(a, b). It should return 12 for mygcd(84, 36).

Show solution
MATLAB
% mygcd.m
function g = mygcd(a, b)
    if b == 0
        g = a;
    else
        g = mygcd(b, mod(a, b));
    end
end

Always write the base case first so the recursion stops. The built-in gcd gives the same answer and handles whole arrays.

12. Optional arguments (Hard)

Write raiseTo(x, p) that raises every element of x to the power p, using p = 2 when the second argument is missing.

Show solution
MATLAB
% raiseTo.m
function y = raiseTo(x, p)
    if nargin < 2 || isempty(p)
        p = 2;
    end
    y = x .^ p;
end

nargin tells you how many arguments the caller supplied. Checking isempty(p) as well lets callers write raiseTo(x, []) to request the default while still passing something in that position.

Python Stand-ins for exercises 9 to 12

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Plots (exercises 13 to 16)

13. Two curves, one axis (Easy)

Plot sin(t) as a solid blue line and cos(t) as a dashed red line for t from 0 to 2 pi. Add axis labels, a title, a legend and a grid.

Show solution
MATLAB
t = linspace(0, 2*pi, 200);
plot(t, sin(t), 'b-', t, cos(t), 'r--')
xlabel('t (radians)'); ylabel('value')
title('Exercise 13'); legend('sin', 'cos'); grid on

linspace gives 200 evenly spaced points, which is smooth enough for a trigonometric curve. Both curves can share one plot call, or you can use hold on between two calls.

14. Bar chart with month names (Easy)

Draw a bar chart of the sales figures [12 15 11 18 21 17] and label the bars with the first six month abbreviations.

Show solution
MATLAB
sales = [12 15 11 18 21 17];
bar(sales)
set(gca, 'XTickLabel', {'Jan','Feb','Mar','Apr','May','Jun'})
ylabel('units (thousands)'); title('Exercise 14')

bar places the bars at x positions 1 to 6, and XTickLabel swaps the numbers for text. In recent MATLAB you can also pass a categorical array as x.

15. Scatter with a fitted line (Medium)

For x = 1:10 and the ten measurements given in the stand-in below, draw the points as a scatter plot and overlay the best straight line.

Show solution
MATLAB
x = 1:10;
y = [2.3 4.1 6.2 7.8 10.4 11.9 14.2 15.8 18.1 20.3];
p = polyfit(x, y, 1);       % [slope intercept]
scatter(x, y)
hold on
plot(x, polyval(p, x), 'r-')
legend('data', 'fit'); title('Exercise 15')

polyfit with degree 1 returns the slope first and the intercept second. hold on keeps the scatter points when the line is added.

16. Filled contour map (Hard)

Plot the function z = x * exp(-x^2 - y^2) on a square from -2 to 2 in both directions, as filled contours with a colorbar.

Show solution
MATLAB
g = linspace(-2, 2, 81);
[X, Y] = meshgrid(g, g);
Z = X .* exp(-X.^2 - Y.^2);
contourf(X, Y, Z, 15)
colorbar; title('Exercise 16')

meshgrid builds the two coordinate grids so that Z can be computed in one vectorized line. Note the dotted operators: each element of the grid is treated separately.

Python Stand-ins for exercises 13 to 16 (matplotlib)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Numerical methods (exercises 17 to 20)

17. Solve a linear system (Easy)

Solve the system 2x + y - z = 8, -3x - y + 2z = -11, -2x + y + 2z = -3 and check the residual.

Show solution
MATLAB
A = [2 1 -1; -3 -1 2; -2 1 2];
b = [8; -11; -3];
x = A \ b                 % 2, 3, -1
norm(A*x - b)             % tiny, around 1e-15

The backslash operator solves the system with a factorization and is more accurate and faster than inv(A)*b. A residual of rounding-error size confirms the answer.

18. Quadratic fit and prediction (Medium)

Fit a degree-2 polynomial to xs = 0:5 and ys = [1.1 2.9 9.2 19.1 33.0 51.2], then predict the value at x = 6.

Show solution
MATLAB
xs = 0:5;
ys = [1.1 2.9 9.2 19.1 33.0 51.2];
p = polyfit(xs, ys, 2)
polyval(p, 6)

polyfit returns coefficients from the highest power down. Predicting outside the fitted range (extrapolation) is risky in general, so treat the number as an estimate.

19. Find a root with fzero (Medium)

Find where the curve cos(x) crosses the line y = x. Give the answer to six decimals.

Show solution
MATLAB
f = @(x) cos(x) - x;
root = fzero(f, [0 1]);
fprintf('%.6f\n', root)       % 0.739085

fzero needs a bracket in which the function changes sign. Here f(0) = 1 is positive and f(1) is negative, so a root must lie in between.

20. Trapezoid error (Hard)

Approximate the integral of sin(x) from 0 to pi (exactly 2) with trapz using 5, 11 and 101 points. Print the error for each.

Show solution
MATLAB
for n = [5 11 101]
    t = linspace(0, pi, n);
    area = trapz(t, sin(t));
    fprintf('%3d points: %.6f  error %.2e\n', n, area, abs(area - 2))
end

Because the trapezoid rule has error proportional to the square of the step size, ten times as many intervals cuts the error by roughly a factor of one hundred. This is a quick way to see the order of a method.

Python Stand-ins for exercises 17 to 20 (SciPy)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

brentq is SciPy's bracketing root finder and plays the role of fzero with a bracket here. np.linalg.solve stands in for the backslash operator.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. In exercise 3, which statement deletes the rows with negative values from M?

    any(M < 0, 2) gives one flag per row, and deleting through a row index with : for the columns removes whole rows. The first option would try to delete single elements and fail on a matrix.
  2. 2. Why does exercise 8 use .^ instead of ^?

    ^ is the matrix power and fails for a row vector. .^ applies the power to each element separately.
  3. 3. What must be true to call fzero(f, [a b]) safely?

    A sign change over the bracket guarantees a root for a continuous function, which is what the algorithm relies on.

Summary

  • Slice with ranges, select with masks and delete with []; combine any and all with a dimension argument for row or column questions.
  • Preallocate before loops, and replace inner loops with a vectorized assignment or a built-in such as cummax and sum.
  • Functions return several outputs by listing them in brackets, and nargin handles optional inputs.
  • Plots are built from a data grid (linspace, meshgrid) plus labels, legends and hold on.
  • Backslash, polyfit, fzero and trapz cover most small numerical tasks.

Next: test your concepts with Interview Questions.