3.2 | Loops

In this section, we start using traditional programming concepts (i.e., conditional statements and loops) in MATLAB. MATLAB supports structured/procedural programming and that is the focus of this course. It also allows you to use object-oriented programming if you are used to working with it. We then look at methods to plot three-dimensional data. Finally, we cover methods for debugging your code as it becomes more complicated.

At the end of this subsection you should be able to:

  1. Determine the time to run a section of code using tic and toc

  2. Implement for-loops and while-loops to control the flow of a program

  3. Fill in values of elements in a vector or matrix in a for-loop

  4. Visualize 3D data using several plotting techniques

Set-Up

Tic & Toc: timing sections of code by employing tic to begin a timer and then toc to check how many seconds (wall time) have elapsed since the last tic.

Loops

As a general rule. If you know how many times a loop will run before entering the loop, use a for loop. If you will not know how many times a loop will run until it begins, use a while loop.

For Loops

For Loops: using for loops in MATLAB be assigning an initial value, final value and step size.

For Loops vs. Vectorization: if you can vectorize an operation you should vectorize an operation. If an operation cannot be vectorized you should be sure to pre-allocate.

Index Variables: most of the time you want your for loop to initialize at 1 and increase its value by 1 until termination. This allows you to use the index to assign values or refer to elements in a vector/matrix. This is also necessary to parallelize your code.

Live Examples

Creating a function to calculate the factorial of a non-negative integer

Creating a function to find the factors of an integer and determine if it is prime

Construct Recamán’s Sequence programmatically (Live Example): Recamán’s sequence defined by

McNugget® Number (Live Example): Chicken McNuggets® currently come in 4, 6, and 10-piece boxes. If you want exactly N nuggets, is there a combination of boxes that you can order to get exactly N? What is a combination that will work? What is the largest N that will not work?

While Loops

While Loops: Using while loops that terminate when the test of a logical statement evaluates as false. This example uses a Fibonacci sequence in the evaluation: more on Fibonacci sequence.

Live Examples

Sandpile Math (Live Example): Create a function that adds (according to sandpile math) two 3×3 matrices consisting of only the values 0, 1, 2, or 3 “grains of sand”. In the resulting matrix, any value greater than 3 will “topple” and give one grain of sand to each non-diagonal neighbor. This process continues until no pile has more than 3 grains.

The Josephus Problem (Live Example): Flavius Josephus, a Jewish soldier and historian, lived in the first century. He fought along with 39 soldiers against Rome in a war, where they were trapped in a cave. The soldiers decided to take their lives instead of being captured by the Romans. They formed a circle such that a person standing on the circle should kill the person next to them and hand over the weapon to next living soldier. This process repeated until only one soldier was left.

Josephus decided he wanted to live and thus placed himself in the 17th position to survive the circle.

Simulate this scenario in Matlab and confirm that Josephus would have survived in that position.

Plots

3D Plots: using plotting tools like mesh, surf and contour to display 3D data: 2 independent variables and one dependent variable. Columns of the dependent variable matrix correspond to “x”-values and rows to “y”-values.

Example 2: creating 3D data given a function of two variables. The first method uses a nested for loop and an alternative method uses a meshgrid. The vectorized meshgrid approach is much faster to run and create, but for some functions, the vectorized approach cannot be employed.

Lecture Code

Additional Examples and Resources