Week 2: MATLAB Functions and Debugging

Today’s Question

How do we turn a formula into reusable, testable code?

Week 2 Plan

  • Meeting 1: formulas, functions, and tests
  • Meeting 2: conditions, loops, boundary cases, and AI debugging

From Formula To Function

  • Name the inputs.
  • Name the outputs.
  • Write the computation once.
  • Test on values where the answer is known.

Meeting 1 Question

What does it mean for code to implement a mathematical definition?

Function Pattern

function y = quadratic_value(a, b, c, x)
    y = a .* x.^2 + b .* x + c;
end

Test Pattern

actual = quadratic_value(1, 0, -1, 0);
expected = -1;
assert(abs(actual - expected) < 1e-12)

Vector Test

x = [-1 0 1];
y = quadratic_value(1, 0, -1, x);

If a function claims to support vectors, test vectors.

Meeting 2 Question

How do we know a generated function matches the intended rule?

Conditional Pattern

if age < 0
    error("Age must be nonnegative.")
elseif age <= 5
    price = 0;
else
    price = 35;
end

Boundary Cases

Piecewise functions are most fragile at thresholds.

Test values exactly at and just around the threshold.

Logical Mask Pattern

temperatures = [18 21 25 29 34 31 22];
hot_mask = temperatures >= 30;
hot_values = temperatures(hot_mask);

A mask is data about the data.

Logical Indexing Pattern

adjusted = temperatures;
adjusted(hot_mask) = 30;

nnz(hot_mask)

Use logical indexing to select, count, or replace values.

Switch Pattern

switch unit
    case "C"
        celsius = value;
    case "F"
        celsius = (value - 32) * 5/9;
    otherwise
        error("Unknown unit.")
end

Use switch when the cases are named choices.

Loop Question

When should code repeat a computation one step at a time?

For Loop Pattern

values = [2 4 6 8];
squares = zeros(size(values));

for k = 1:numel(values)
    squares(k) = values(k)^2;
end

Use a for loop when the number of repetitions is known.

Accumulator Pattern

total = 0;

for k = 1:numel(values)
    total = total + values(k);
end

An accumulator must be initialized before the loop.

While Loop Pattern

total = 0;
n = 0;

while total < 100
    n = n + 1;
    total = total + n^2;
end

Use a while loop when repetition depends on a condition.

While Loop Guard

max_steps = 1000;

while total < 100 && n < max_steps
    n = n + 1;
    total = total + n^2;
end

A generated while loop without a guard deserves suspicion.

Loop Or Vectorize?

squares_loop = zeros(size(values));
for k = 1:numel(values)
    squares_loop(k) = values(k)^2;
end

squares_vector = values.^2;

In MATLAB, the vectorized version is often clearer.

Loop Debugging Habit

Check:

  • first iteration;
  • last iteration;
  • accumulator initialization;
  • stopping condition;
  • array size.

Debugging Habit

Before trusting a function, test:

  • scalar input;
  • vector input;
  • boundary cases;
  • loop edge cases;
  • impossible or unexpected input.

Plausible But Weak Code

function area = circle_area(radius)
    area = 3.14 * radius^2;
end

Critique Questions

  • Does it use pi?
  • Does it support vector input?
  • What happens for negative radius?
  • Is a loop needed?
  • Which tests would reveal the problem?

Survival Rule

Generated functions often look plausible. The test cases decide whether they are correct.

Exit Ticket

A function is trustworthy enough to reuse when …