Week 2: MATLAB Programming and Functions
Official Topic
MATLAB programming and user functions.
Problem Focus
How do we turn a formula into reusable, testable code?
Students write small functions, use conditionals and loops when appropriate, and practice checking output on simple cases before trusting the code.
Learning Goals
By the end of the week, students should be able to:
- read and write simple MATLAB functions with clear inputs and outputs;
- distinguish scripts, local functions, and function files;
- use
if,elseif,else, and logical conditions for piecewise rules; - use logical masks to select, count, and replace array elements;
- use
switch,case, andotherwisefor a small set of named choices; - write
forloops for repeated calculations; - use
whileloops with a clear stopping condition and a guard against infinite loops; - trace accumulator variables and preallocated arrays;
- explain when a vectorized expression is better than a loop;
- write tests for known values, boundary cases, and vector inputs;
- recognize common bugs in AI-generated functions;
- document the checks performed before trusting a function.
Meeting 1: From Formula To Function
Question: What does it mean for code to implement a mathematical definition?
Suggested 75-minute rhythm:
| Time | Activity |
|---|---|
| 0-8 min | Warm-up: read a function signature and predict outputs |
| 8-25 min | Live coding: scalar formula to vectorized function |
| 25-40 min | Script plus local functions: where tests should live |
| 40-55 min | Student task: add tests for a quadratic function |
| 55-68 min | Boundary cases: zeros, negatives, and unexpected inputs |
| 68-75 min | Exit ticket: one test you trust and why |
Core MATLAB Pattern
values = [-2, -1, 0, 1, 2];
outputs = quadratic_value(1, 0, -1, values);function y = quadratic_value(a, b, c, x)
y = a .* x.^2 + b .* x + c;
endMeeting 2: Conditions, Loops, Debugging, And AI Review
Question: How do we know a generated function matches the intended rule?
Suggested 75-minute rhythm:
| Time | Activity |
|---|---|
| 0-10 min | Review: function input/output contracts |
| 10-24 min | Live coding: piecewise rules with if and logical conditions |
| 24-34 min | Logical indexing: select and repair values with masks |
| 34-48 min | Loop patterns: for, accumulators, and preallocation |
| 48-58 min | while loops: stopping conditions and iteration guards |
| 58-66 min | AI debugging activity: inspect plausible generated code |
| 66-72 min | Lab work: repair code and add tests |
| 72-75 min | Exit ticket: a loop or boundary case students now check |
In-Class Checks
- Define function inputs and outputs.
- Use relational and logical operators.
- Create logical masks such as
x > 0. - Use logical indexing to select, count, or replace elements.
- Use
switchfor a fixed set of named cases. - Use
forloops when the number of repetitions is known. - Use
whileloops when repetition depends on a condition. - Initialize accumulator variables before a loop.
- Preallocate arrays before filling them in a loop.
- Write short tests for known values.
- Debug common mistakes in generated or student-written code.
- Check scalar input, vector input, and boundary values.
- Decide whether a function should reject invalid input.
AI-Aware Task
Ask an LLM to write a MATLAB function for a piecewise mathematical formula. Then test boundary cases and decide whether the generated implementation matches the intended definition.
Survival Checklist
These are the Week 2 MATLAB habits you should be able to recognize, test, and repair without relying on AI.
Commands And Patterns To Own
| Pattern | What you should know |
|---|---|
function out = name(in) |
Defines a function contract: inputs in, outputs out. |
if, elseif, else, end |
Selects code based on conditions. |
switch, case, otherwise |
Selects among a small set of named cases. |
for k = 1:n |
Repeats code a known number of times. |
while condition |
Repeats code until a condition becomes false. |
total = total + value |
Updates an accumulator variable. |
values = zeros(1, n) |
Preallocates space before filling an array. |
numel(x) |
Counts elements in an array. |
&&, ||, ~ |
Scalar logical AND, OR, and NOT. |
&, | |
Elementwise logical AND and OR for arrays. |
mask = x > 0 |
Creates a logical array with the same shape as x. |
x(mask) |
Selects elements where the mask is true. |
x(mask) = value |
Replaces elements where the mask is true. |
nnz(mask) |
Counts how many logical entries are true. |
input, disp, fprintf |
Handles simple interactive or formatted communication. |
assert(condition) |
Stops execution if a test fails. |
error("message") |
Stops execution with a clear message. |
abs(actual - expected) < tol |
Compares floating-point numbers with tolerance. |
Mistakes To Catch
- Writing
x^2when vector input requiresx.^2. - Testing only one convenient input.
- Forgetting boundary cases such as
0, negative values, or threshold values. - Returning an output variable that was never assigned.
- Using scalar
iflogic on a vector without thinking about dimensions. - Creating a logical mask whose size does not match the array being indexed.
- Forgetting that
&&and||are for scalar conditions, not array masks. - Writing a
switchwith nootherwisecase. - Starting a loop at the wrong index.
- Forgetting to initialize or update an accumulator.
- Writing a
whileloop with no reliable stopping condition. - Growing an array inside a loop when it could be preallocated.
- Using a loop when a short vectorized expression would be clearer.
- Trusting code because it works once in the Command Window.
Checks Before Trusting A Function
- State the input/output contract in one sentence.
- Test at least one value where the answer is known by hand.
- Test a boundary value.
- Test a vector input if the function claims to support vectors.
- For logical indexing, check the mask with
nnz(mask)or by displaying selected values. - For loops, test the first iteration, last iteration, and an empty or tiny input when relevant.
- For
whileloops, state the stopping condition and a maximum number of iterations. - Decide what invalid input should do.
- Run the script from a clean workspace.
Exercises
Complete the Week 2 exercises after the lab.
Materials
- Slides
- Starter code: week02_function_tests.m
- Piecewise function script: week02_piecewise_validation.m
- Loop patterns script: week02_loop_patterns.m
- Logical indexing and switch script: week02_logical_indexing_switch.m
- AI debugging script: week02_ai_function_review.m
- Lab 2
- AI debugging activity