Lab 2: MATLAB Functions And Tests
Goal
Write small MATLAB functions and build a habit of testing them before reuse.
Setup
Work in a folder called week02. Start scripts from a clean workspace:
clear; clc; close all;Part A: Run And Explain
Open week02_function_tests.m.
Run the script and answer:
- What function is being tested?
- What values are used as test inputs?
- Which test would fail if the function used
x^2instead ofx.^2? - Why is a vector test useful?
Part B: Add Tests
Add tests for:
quadratic_value(1, 0, -1, 1);quadratic_value(1, 0, -1, -1);quadratic_value(0, 2, 3, [0 1 2]).
Use either assert or a helper function that compares actual and expected values.
Part C: Piecewise Function
Open week02_piecewise_validation.m.
The script computes ticket prices from ages. Modify it to:
- Add tests for every boundary age.
- Reject negative ages.
- Explain why the thresholds are easy places for bugs.
Part D: Invalid Input
Decide what your function should do for:
age = -3;age = 17.5;age = [5 6 18 65].
Write a short note explaining which cases your implementation supports and why.
Part E: Loop Patterns
Open week02_loop_patterns.m.
Run the script and answer:
- Which section uses a
forloop? - Which section uses an accumulator?
- Which section uses a
whileloop? - What guard prevents the
whileloop from running forever? - Which computation is clearer when written in vectorized MATLAB?
Modify the script so that the while loop stops when the accumulated sum is at least 500 instead of 100.
Record the final value of n and the final accumulated sum.
Part F: Logical Indexing And Switch
Open week02_logical_indexing_switch.m.
Run the script and answer:
- What does the logical mask represent?
- What does
nnz(hot_mask)count? - Which values are changed in
adjusted? - What input choices does the
switchblock accept?
Modify the script so that it caps values above 28 instead of values at least 30.
Deliverable
Submit one MATLAB script containing:
- at least one function;
- at least five tests;
- one boundary-case test;
- one logical-indexing example or a written explanation of why it is not needed;
- one loop or one vectorized replacement with an explanation;
- one vector-input test or a written explanation of why vector input is not supported.
Reflection
Answer:
- What is the input/output contract of your function?
- Which test gave you the most confidence?
- Which input would you still be nervous about?
AI Use
If you ask an LLM for a function, include:
- the prompt;
- the generated code;
- at least two tests that caught or could have caught a mistake.