Week 2 – Programming Basics: Loops, Conditionals, Functions

Learning Outcomes By the end of this week, students will be able to:

  1. Use if/else statements.
  2. Write for and while loops.
  3. Create MATLAB functions.
  4. Debug and profile MATLAB code.
  5. Understand good coding practices for reproducibility.

Suggested Readings

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