Week 2
Week 2 – Programming Basics: Loops, Conditionals, Functions
Learning Outcomes By the end of this week, students will be able to:
- Use
if
/else
statements. - Write
for
andwhile
loops. - Create MATLAB functions.
- Debug and profile MATLAB code.
- Understand good coding practices for reproducibility.
Suggested Readings
- Frain, MATLAB for Economics and Econometrics, Ch. 4 (Programming structures), Ch. 7 (Functions).
- MatlabCheatSheet.pdf - Loops section.
- TutorialMatlab.pdf – Sections 5–7 (loops, functions, debugging).
In-Class Activities
- Write a loop to compute the first 10 Fibonacci numbers.
- Implement a function compound_interest(P, r, n) that calculates final capital.
- Add an if statement to handle invalid inputs.
- Use MATLAB’s debugging tools: breakpoints, dbstop if error.
- Time a loop vs. vectorized code with tic/toc.
Homework / Practice
- Create a function that simulates GDP growth over T periods given an initial GDP, growth rate, and random shocks.
- Write a script that:
- Simulates 100 GDP paths.
- Calculates mean and variance of final GDP.
- Plots histogram of results.
- Document your code with comments and save outputs to a figure file.
Files
- Slides Week 2 – Slides from lecture.
- week2.m – Example script from lecture.
- week2_debug.m – Example debug script from lecture.
- compound_interest.m – Example function from lecture.
- gdp_simulate_starter.m – Starter function file for in class challenge.
- week2_challenge_starter.m – Starter file for in class challenge.
- week2_homework_starter.m – Starter file for homework.