Scripts and Control Flow

Overview

In this module, we will learn about pseudocode, scripts and control elements. We will also begin to dabble in some light MATLAB programming.

This module is broken down into the following sections:

Learning Objectives

  • Define Pseudocode and be able to write pseudocode
  • Be able to create a script and add comments
  • Recognize MATLAB syntax highlighting colors in scripts (eg. blue vs green or red vs orange).
  • List the common control flow statements and describe their similarities and differences

Important Terminology

  • Pseudocode – fake computer coding – written in easy to read steps, as opposed to precise programming syntax
  • Script: A text file you create that contains a series of MATLAB commands (or statements).
  • Control Flow: the process of creating conditional statements or looping statements.

MATLAB Conditional Statements

Special MATLAB Characters

  • % – percent signs indicate comments (text that is not run as a MATLAB command)
  • %% – double percent signs indicate code blocks in scripts
  • ; – semicolon. End of line. Suppress output to the command window

MATLAB Key words

  • for
  • while
  • end
  • if
  • else
  • return
  • continue
  • break

Pseudocode

TOP | Pseudocode | Scripts | Control Flow

Pseudocode is a useful brainstorming technique to use when you are trying to figure out how to organize an algorithm or small piece of code. Pseudocode typically follows the structure of code but uses normal language structure. You can write pseudocode by hand or in any text editor.

For example, the following pseudocode outlines the algorithm that I use to create a cup of tea:

  1. Turn on Electric Kettle
  2. Inspect mug for reasonable cleanliness
  3. Add 1 packet of Splenda to mug
  4. Add 1 teabag (Double Spice Chai) to mug
  5. Wait for water to boil
  6. Add 1 cup of water to mug
  7. Wait 3 minutes
  8. Discard teabag
  9. Enjoy delicious tea

Notice that this pseudocode has a sequential structure – each step waits for the previous step to complete before continuing. Also note that there is a VERB (a function) and a quantifiable quantity (variable): 1 packet of Splenda, 1 teabag, etc.

While my tea-making algorithm may look familiar, there are other sequences that can result in an equally as tasty cup of tea. There often are multiple solutions to a problem, which is why writing out pseudocode before you start actually coding is a useful exercise. Sometimes a more efficient sequence may reveal itself after explicitly writing out the steps that you wish to accomplish.

Scripts

TOP | Pseudocode | Scripts | Control Flow

no_regerts
no_regerts

A script is simply a collection of MATLAB commands. Scripts can be used to code small, simple algorithms. Importantly, you can save a MATLAB script as a text document (using an extension of .m) for use at a later date.

In a script, MATLAB executes the first line and then marches sequentially down each line, like in our pseudocode from the previous section.

You can exclude lines in your script from being executed by prefacing the line with the percent sign: %. Lines in the script that begin with a percent sign are colored green. These lines of text are typically used as comments. Comments are a great way to add structure to your script and help clarify your code so that you (or other people) can figure out what your code is supposed to do.

Lines that start with a double percent sign create code sections. These lines are also not executed. Special commands in MATLAB can be used to only execute the code inside a code section—as opposed to running all of the lines in the entire script—thereby allowing you to break your script down into smaller executable sections.

Error Checking

TOP | Pseudocode | Scripts >> Error Checking | Script Example

Checking Code for Errors and Warnings

The script editor uses colors to indicate a class or keyword, or to highlight an error. This coloring is very useful when you are looking for programming errors. There is also a message indicator on the right side of the editor that highlights on which line the errors are located. To see a list of all the colors used, open the preferences in MATLAB. Click on the Colors tab. The “MATLAB Colors preferences” determines the syntax coloring scheme. It is also a useful reference when you are learning to code in MATLAB.

matlab_prefs_colors
matlab_prefs_colors

Script Example

TOP | Pseudocode | Scripts >> Error Checking | Script Example

The easiest way to understand a script is to make one. Let’s make a very simple script.

This script will find the even values in an array of numbers using some simple mathematical calculations and class typecasting.

First, we’ll write the Pseudocode:

1. Clear the workspace and command window
2. assign to the variable 'a' the values 1 through 20
3. Divide each element in 'a' by 2 and return the remainder. Assign those returned results to 'b'.
4. typecast the LOGICAL NOT of 'b' to a logical class and assign the results to 'c'
5. Index 'a' using the logical array 'c'

Ok, so now, we’ll create a new script in MATLAB execute the steps in our pseudocode.

First, click on the “New Script” button, under the “Home Tab” in MATLAB.

mlb_home_new_script
mlb_home_new_script

Note, when you do this that you should now see an “editor” tab in the MATLAB desktop and an empty ‘untitled’ document in the “Editor” Window.

mlb_editor
mlb_editor

Add the following lines to this script:

clear all
clc
a = 1:20
b = mod(a,2)
c = ~logical(b)
d = a(c)

Right-click anywhere on the script and select (“Evaluate Current Section”). Notice that all four lines are executed sequentially, the results are displayed in the Command Window, and that the variables now show up in the Workspace

  • What do you think mod does? What values are returned for odd numbers? For even?
  • Why did we use the function logic during the assignment of c?
  • What does the ‘~’ symbol in front of logic do?
  • What is in d? What is the sum of d?

Adding Comments and semi-colons to your script

Use the % and %% to add comments and code sections respectively. Comments are used to explain (and remind yourself) what you are trying to accomplish with a particle piece of code.

The %% percent signs indicate a new code section within the same script. Only code sections in between %% percent sign blocks are run when you execute (by right-clicking) “Evaluate current selection”

Use the semi-colon at the end of each line to suppress output to the command window.

For example, let’s add some code sections, comments, and semi-colons to our simple script from above.

%% Code Block 1 - clear command window and workspace
clear all
clc

%% Code Block 2 - assign values to variables
a = 1:20; % assign the values 1 through 20 to a
b = mod(a,2); % create a new array of remainders after division by 2
c = ~logical(b); % convert b to a logical array and apply logical NOT
d = a(c); % index *a* with the logical array *c*

%% Code Block 3 - calculate the sum of *d*
e = sum(d); % calculates the sum of *d*

Click on the different code blocks on your updated script. See how a code section becomes highlighted when you click on it? To run a code section, click anywhere inside the code block (it should highlight when you click on a code block ). Right-click and select “Evaluation Current Section.”

  • What runs when you select “Evaluation Current Section?”
  • What do you see in the command window?

Control Flow

TOP | Pseudocode | Scripts | Control Flow

now_leak_proof
now_leak_proof

Control flow is the process of creating conditional statements or looping statements. Conditional statements compare values of variables to determine which block of code should be executed. This is useful for handling unknowns. If this, do this or if that, do that, otherwise, do this and so forth.

For looping statements, a number of loops are executed, repeating the code block over and over again. Computers are really good at repeating tasks over and over. This can be useful for building arrays.

For more information on Control flow, please refer the relevant MATLAB documentation. Also, please familiarize yourself with the following documentation on the control flow KEYWORDS.

Conditional Statements

TOP | Control Flow >> Conditional Statements | Loops

xkcd
xkcd

Conditional statements enable a function to decide which block of code to execute. Conditional statements execute based on the result of a relational operation.

IF ELSE statements

TOP | Control Flow >> Conditional Statements >> IF ELSE statements | SWITCH CASE

If, else conditional statements are the simplest and most straight forward. An if, else conditional statement is bracketed by the if and the end keywords, as follows:

if conditional statement

CODE BLOCK 1

else

CODE BLOCK 2

end

CODE BLOCK 1 runs only if the conditional statement returns TRUE. Otherwise, CODE BLOCK 2 will run.

Consider the following example:

%% EXAMPLE if, else 

x = input('Enter a number: ')

if mod(x,2) == 1
    display('x is odd')
else
    display('x is even')
end

The input function requests user input from the command window. After executing this code section, you will get a prompt in the command window to enter a number.

The mod function returns the modulus after division (remainder after division by the second indicated input). So, if you input the number 5, mod(5,2) returns the remainder after 5 is divided by 2, which is 1.

The “==” is the conditional statement that asks whether the result of mod(5,2) is equal to 1. Since it is, the conditional statement returns TRUE and the code block: display(‘x is odd’) is executed.

  • Explain what happens when you change x to 6?

For more information on IF ELSE statements, refer to the matlab documentation.

SWITCH CASE

TOP | Control Flow >> Conditional Statements >> IF ELSE statements | SWITCH CASE

Switch, case conditional statements are best used when you have a character array you want to compare

%% Example Switch, Case
channel = input('Enter a color: ','s')

switch channel
    case 'red'
        display('Roses are red')
    case 'green'
        display('Stems are green')
    case 'blue'
        display('Violets are blue')
    otherwise
        display('try again')
end

In this example, we add a second input,’s’, to the function input so that the data is treated as a string.

After entering a color name, the Switch, Case block will scan down to each case looking for a match. If a match is found, that particular code block and ONLY that code block will be executed. If no match is found, then the “otherwise” code block will be executed. Note, the match is case-sensitive. That is, if you enter ‘Red’, then you will not get a match.

For more information on SWITCH CASE statements, refer to the MATLAB documentation.

Loops

TOP | Control Flow >> Conditional Statements | Loops

loop_arrow
loop_arrow

FOR Loops

TOP | Control Flow >> Loops >> FOR Loops | WHILE Loops

For Loops iterate a code block for a predetermined number of times.

For example, consider the following:

for n = 1:10
    display(n)
end

These 3 lines set up an entire for loop. The first line

for n = 1:10

creates the predetermined number of loops by creating a numeric array. In this case, the array 1 to 10. This line must start with the keyword for. The number of times that the for loop will loop is equal to the number of columns in n. In this case, 10 times.

The second line

display(n)

is the executed code block that uses the function display to display the current value of n. Notice how during each execution of the code block, the value of n is actually just a single number (and not the full array). Each time that the loop runs, the value of n changes to the value found in the next column of the array assigned in the for line.

The third line

end

terminates the for loop. end is another critical keyword and must be the last line of the for loop.

Important Notes About For Loops
  • The For Loop loops for the number of times that there are columns in the array (not the maximum value in the array)
  • you can use any variable name for the array assignment (n and i are popular variable names for For Loops)
  • The For Loop array does not have to start with the value 1

Consider the following:

for m = 2:2:10
    display (m)
end

  • How many times does this For Loop loop?
  • What values does m have during each loop?
Memory Considerations

For Loops are often used to fill arrays in some sequential fashion, such as element by element or row by row. When doing this, it is best to preallocate the array you want to fill with zeros. Otherwise, MATLAB has to create copies of the variables on each sequential run of the loop which takes time and memory.

If you know how big your final array is going to be, preallocation is easily accomplished using the function zeros.

For example:

i = zeros(1,10)

Creates an array i with 10 zeros. Then you can fill the elements of i using a For Loop as follows:

i = zeros(1,10)
for n = 1:10
    i(n) = n*10
end

As you can see in the Command Window output, each run of the For Loop adds a multiple of n into the nth element of i.

Vectorization, it is often possible to vectorize a For Loop in MATLAB. Always try to vectorize your code whenever possible as the vectorized form of the code can run faster than the For Loop form.

j = [1:10] * 10

accomplishes the same thing as the previous loop, but using only one line of code

Combining Conditional Statements and for Loops

Control Flow functions are often used in combination. Consider the following:

for x = 1:10
    if mod(x,2)
        eo = 'odd';
    else
        eo = 'even';
    end

    fprintf('\nThe number %d is %s\n',x,eo)
end

Similar to the sprintf function that we first learned about in the character section, fprintf can format data into strings. In addition, fprintf can then output those strings to the command window (or even to files). In this syntax, \n means new line, %d is a placeholder for a number (the value from x) and %s a placeholder for a string (the value from eo)

WHILE Loops

TOP | Control Flow >> Loops >> FOR Loops | WHILE Loops

While Loops are very similar to For Loops except that instead of establishing a predetermined number of loops, while loops continue to execute until the conditional statement returns a false.

Let’s modify one of our previous For Loops into a while loop.

display('Go, go while loop!')
x = '';
while ~strcmp(x,'stop')

    x = input('Enter a number: ');

    if isnumeric (x)

        if mod(x,2)
            eo = 'odd';
        else
            eo = 'even';
        end

        fprintf('The number %d is %s\n',x,eo)
    else
        fprintf('The input %s is not a number!\n',x)
    end

end

The conditional statement is:

strcmp(x,'stop')

The function strcmp compares two strings and only returns TRUE if an exact match is found. Since we are using the logical operator NOT (‘~’) in front of strcmp, this conditional statement will return a FALSE when x matches ‘stop’. Note: you must include the single quotes when entering ‘stop’ or the input function will not recognize the input as a character array (it will assume you are inputting a variable name).

Also, notice that we had to preallocate x with an empty string (”), so that the while loop would have something to compare on the first run.

The if, else statement uses the function isnumeric to determine if a number has been inputed. If x is a number, then isnumeric returns true and the if code block executes. In this case, the if code block contains a nested if, else statement. This statement uses the function mod to get a remainder from x after dividing by 2. If x is odd, mod returns a 1 and the statement jumps to the if code block. If x is even, there is no remainder after division by two, and mod returns a zero, and the if, else statement jumps to the else part.

  • What happens after you type ‘stop’? Does the code block run one last time?
  • How could you suppress output to the command window if x = ‘stop’?
  • how would you make this while loop case-insensitive?

USEFUL TO KNOW: Sometimes while loops can be trapped in an unbreakable loop (usually due to shoddy programming). To forcefully break out of a while loop, press Ctrl-C.

END

TOP | Pseudocode | Scripts | Control Flow