MATLAB Exercises
Time to practise! Each exercise has a starter playground that runs as-is and prints a placeholder result, so you can see the expected format. Copy it into MATLAB or Octave (the playgrounds on this site are simulated), replace the TODO parts, and compare your output with the "Expected" lines. Try for a few minutes before opening the solution.
| # | Exercise | Topics |
|---|---|---|
| 1 | Temperature table | vectors, element-wise math, fprintf |
| 2 | Multiples of 3 or 5 | colon operator, logical indexing |
| 3 | FizzBuzz | for loops, if/elseif, mod |
| 4 | Vowel counter | char arrays, ismember, functions |
| 5 | Grade report | matrices, matrix product, find |
| 6 | Word frequency | strsplit, unique, accumarray |
| 7 | Mixing problem | linear systems, backslash |
| 8 | Inventory value | struct arrays, sorting |
| 9 | Find the root | function handles, fzero, while loops |
1. Temperature table
Create a vector of Celsius temperatures from 0 to 40 in steps of 10, convert them with F = C * 9/5 + 32 (no loop!) and print a table with fprintf, each row formatted as 0 C = 32.0 F.
Expected first line: 0 C = 32.0 F, last line: 40 C = 104.0 F.
C = 0; % TODO: all temperatures 0, 10, ..., 40
F = 0; % TODO: convert
fprintf('%d C = %f F\n', C, F); % TODO: fix the format and print all rows0 C = 0.000000 F
Show solution
C = 0:10:40;
F = C * 9/5 + 32;
fprintf('%3d C = %5.1f F\n', [C; F]);Stacking [C; F] puts each pair in one column, the order in which fprintf consumes values.
2. Multiples of 3 or 5
Find the sum of all positive integers below 1000 that are multiples of 3 or 5, without a loop.
Expected: 233168
n = 1:999;
mask = false(size(n)); % TODO: true where n is a multiple of 3 or of 5
disp(sum(n(mask)))0
Show solution
n = 1:999;
mask = mod(n, 3) == 0 | mod(n, 5) == 0;
disp(sum(n(mask))) % 2331683. FizzBuzz
For the numbers 1 to 15, print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, and the number otherwise, all on one line separated by spaces.
Expected: 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
for k = 1:15
% TODO: choose the right word
fprintf('%d ', k);
end
fprintf('\n');1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Show solution
for k = 1:15
if mod(k, 15) == 0
fprintf('FizzBuzz ');
elseif mod(k, 3) == 0
fprintf('Fizz ');
elseif mod(k, 5) == 0
fprintf('Buzz ');
else
fprintf('%d ', k);
end
end
fprintf('\n');Test for 15 first: otherwise the mod(k, 3) branch would catch 15 and print Fizz.
4. Vowel counter
Write a local function count_vowels(s) that returns how many vowels (a, e, i, o, u, upper or lower case) a char array contains.
Expected: 6 and 5.
disp(count_vowels('Programming in MATLAB'))
disp(count_vowels('AEIOU xyz'))
function n = count_vowels(s)
n = 0; % TODO: count the vowels in s
end0
0
Show solution
disp(count_vowels('Programming in MATLAB')) % 6
disp(count_vowels('AEIOU xyz')) % 5
function n = count_vowels(s)
n = sum(ismember(lower(s), 'aeiou'));
endismember on a char array checks each character, and sum counts the trues.
5. Grade report
Each row of marks holds one student's marks in homework, midterm and final exam, weighted 20%, 30% and 50%. Compute every student's weighted score with one matrix product, then print the score of each student and the numbers (row indices) of the students below 60.
Expected:
Student 1: 79.6
Student 2: 55.4
Student 3: 90.4
Student 4: 58.0
Below 60: [2 4]marks = [80 72 84
60 58 52
95 88 90
40 65 61];
weights = [0.2 0.3 0.5];
score = zeros(4, 1); % TODO: one matrix product
fprintf('Student %d: %.1f\n', [1:4; score']);
fprintf('Below 60: %s\n', 'TODO'); % TODO: mat2str of the students' numbersStudent 1: 0.0
Student 2: 0.0
Student 3: 0.0
Student 4: 0.0
Below 60: TODO
Show solution
marks = [80 72 84; 60 58 52; 95 88 90; 40 65 61];
weights = [0.2 0.3 0.5];
score = marks * weights'; % 4x3 times 3x1 = 4x1
fprintf('Student %d: %.1f\n', [1:4; score']);
fprintf('Below 60: %s\n', mat2str(find(score < 60)'));6. Word frequency
Count how often each word appears in sentence (ignoring case) and print every distinct word with its count, in alphabetical order. Use unique with its third output and accumarray.
Expected:
and: 1
cat: 2
dog: 1
ran: 1
saw: 1
the: 3sentence = 'The cat saw the dog and the cat ran';
words = strsplit(lower(sentence));
% TODO: find the distinct words and count each one
fprintf('%d words in total\n', numel(words));9 words in total
Show solution
sentence = 'The cat saw the dog and the cat ran';
words = strsplit(lower(sentence));
[vocab, ~, idx] = unique(words);
counts = accumarray(idx(:), 1);
for k = 1:numel(vocab)
fprintf('%s: %d\n', vocab{k}, counts(k));
end7. Mixing problem
A café mixes three coffee blends. Each kilogram of blend A, B and C contains these amounts (kg) of three bean types:
| Bean | A | B | C | Needed |
|---|---|---|---|---|
| Arabica | 0.5 | 0.2 | 0.3 | 31 |
| Robusta | 0.3 | 0.6 | 0.2 | 34 |
| Liberica | 0.2 | 0.2 | 0.5 | 35 |
How many kg of each blend use exactly the available beans? Set up A·x = b and solve it with backslash.
Expected: A = 20.0 kg, B = 30.0 kg, C = 50.0 kg
A = eye(3); % TODO: the coefficient matrix
b = [31; 34; 35];
x = zeros(3, 1); % TODO: solve
fprintf('A = %.1f kg, B = %.1f kg, C = %.1f kg\n', x);A = 0.0 kg, B = 0.0 kg, C = 0.0 kg
Show solution
A = [0.5 0.2 0.3
0.3 0.6 0.2
0.2 0.2 0.5];
b = [31; 34; 35];
x = A \ b;
fprintf('A = %.1f kg, B = %.1f kg, C = %.1f kg\n', x);Each row of A is one bean type; each column one blend.
8. Inventory value
items is a struct array with fields name, price and qty. Print each item's total value (price * qty), sorted from the most to the least valuable, then the grand total.
Expected:
Laptop 4500.00
Monitor 960.00
Keyboard 225.00
Mouse 150.00
Total 5835.00items = struct('name', {'Mouse', 'Laptop', 'Keyboard', 'Monitor'}, ...
'price', {25, 900, 45, 240}, ...
'qty', {6, 5, 5, 4});
value = zeros(1, numel(items)); % TODO: [items.price] .* [items.qty]
order = 1:numel(items); % TODO: sort descending
for k = order
fprintf('%-9s %8.2f\n', items(k).name, value(k));
end
fprintf('%-9s %8.2f\n', 'Total', sum(value));Mouse 0.00
Laptop 0.00
Keyboard 0.00
Monitor 0.00
Total 0.00
Show solution
items = struct('name', {'Mouse', 'Laptop', 'Keyboard', 'Monitor'}, ...
'price', {25, 900, 45, 240}, ...
'qty', {6, 5, 5, 4});
value = [items.price] .* [items.qty];
[~, order] = sort(value, 'descend');
for k = order
fprintf('%-9s %8.2f\n', items(k).name, value(k));
end
fprintf('%-9s %8.2f\n', 'Total', sum(value));Passing cell arrays to struct creates one element per cell, a quick way to build a struct array.
9. Find the root
Find the positive root of f(x) = x³ − x − 2 in two ways: with fzero, and with your own bisection loop on the interval [1, 2] that halves the interval until it is shorter than 1e-8.
Expected (both lines): 1.52137971
f = @(x) x.^3 - x - 2;
lo = 1; hi = 2;
% TODO: while the interval is longer than 1e-8, keep the half where f changes sign
fprintf('bisection: %.8f\n', (lo + hi) / 2);
fprintf('fzero: %.8f\n', 0); % TODObisection: 1.50000000
fzero: 0.00000000
Show solution
f = @(x) x.^3 - x - 2;
lo = 1; hi = 2;
while hi - lo > 1e-8
mid = (lo + hi) / 2;
if f(lo) * f(mid) <= 0
hi = mid; % sign change in the left half
else
lo = mid;
end
end
fprintf('bisection: %.8f\n', (lo + hi) / 2);
fprintf('fzero: %.8f\n', fzero(f, [1 2]));Test yourself
Which expression sums the elements of v that are greater than 10?
sum(v > 10)sum(v(v > 10))v(sum > 10)find(v > 10)
In FizzBuzz, why must the multiple-of-15 test come first?
- It is faster
- Otherwise 15 would match the multiple-of-3 branch first
- mod only works with 15
- It doesn't matter
What does [items.price] produce for a struct array items?
- The first price
- A row vector of all prices
- A cell array of prices
- An error