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;
end

Answer:

  1. What are the inputs?
  2. What is the output?
  3. What is returned by affine_value(2, -1, 4)?
  4. What is returned by affine_value(2, -1, [0 1 2])?
  5. Why is .* used?

Exercise 2: Write Tests

For:

function y = square_shift(x)
    y = x.^2 - 4;
end

Write 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:

  1. creates a logical mask for temperatures at least 30;
  2. extracts the hot temperatures;
  3. counts the hot temperatures with nnz;
  4. creates a copy where every value above 30 is replaced by 30.

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:

  1. Creates values = [1 2 3 4 5].
  2. Preallocates an array called squares.
  3. Uses a for loop to fill squares with the square of each value.
  4. Checks the result with assert.
  5. 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 while loop;
  • 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;
end

Find 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?