3.1 | Conditional Statements

In this subsection, 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 section you should be able to:

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

  2. Evaluate if a Boolean expression is true or false using logical comparisons

  3. Use the find function to determine indices where a logical comparison is true

  4. Implement if-statements to control the flow of a program

Set-Up

Logical Tests: comparisons that return a “0” (false) or “1” (true) when comparing two quantities with ==, <, >=, etc. These are also known as booleans. We can compare two statements (i.e. true or false) with & and | and get a result according to the truth table.

Find: use the find command to locate indices where a logical test evaluates as true (1).

Conditional Statements

Conditional Statements: controlling the flow of the programming by running sections of code only when a logical test returns “true”. In Matlab, we use if, elseif and else statements.

Example 1: Using if statements to construct a piecewise function.

Flowcharts

Leap Year

Creating a function to determine if a given year is a leap year

Fizzbuzz