Week 2 Exercises
These exercises practice functions, conditions, loops, and tests. Use AI only after you have written a first attempt yourself.
Exercise 1: Read A Function
Given:
function y = affine_value(m, b, x)
y = m .* x + b;
endAnswer:
- What are the inputs?
- What is the output?
- What is returned by
affine_value(2, -1, 4)? - What is returned by
affine_value(2, -1, [0 1 2])? - Why is
.*used?
Exercise 2: Write Tests
For:
function y = square_shift(x)
y = x.^2 - 4;
endWrite tests for:
x = 0;x = 2;x = -2;x = [0 2 -2].
Use assert.
Exercise 3: Piecewise Rule
Write a function ticket_price(age) using this rule:
| Age | Price |
|---|---|
| less than 0 | error |
| 0 to 5 | 0 |
| 6 to 17 | 20 |
| 18 to 64 | 35 |
| 65 or more | 25 |
Test boundary ages: -1, 0, 5, 6, 17, 18, 64, 65.
Exercise 4: Logical Indexing
Let:
temperatures = [18 21 25 29 34 31 22];Write MATLAB code that:
- creates a logical mask for temperatures at least
30; - extracts the hot temperatures;
- counts the hot temperatures with
nnz; - creates a copy where every value above
30is replaced by30.
Explain why this does not need a loop.
Exercise 5: Switch
Write a small switch block that converts a value to Celsius when unit is "C" or "F".
Include an otherwise case that raises an error for an unknown unit.
Exercise 6: Write A For Loop
Write MATLAB code that:
- Creates
values = [1 2 3 4 5]. - Preallocates an array called
squares. - Uses a
forloop to fillsquareswith the square of each value. - Checks the result with
assert. - Writes the equivalent vectorized expression.
Answer: which version is easier to read?
Exercise 7: Accumulator And While Loop
Write MATLAB code that finds the smallest positive integer n such that:
1^2 + 2^2 + ... + n^2 >= 500
Use:
- an accumulator variable;
- a
whileloop; - a maximum-iteration guard.
Report n and the final accumulated sum.
Exercise 8: Debug Generated Code
An LLM produced:
function area = circle_area(radius)
area = 3.14 * radius^2;
endFind at least three issues or limitations. Write a corrected version and tests.
Exercise 9: Explain A Failure
Run:
x = [1 2 3];
y = x^2;Explain the error in words. Then fix it.
Exit Ticket
Write 3-5 sentences answering:
What makes a function trustworthy enough to reuse?