Skip to main content
Engineering LibreTexts

4.8: Flow Control

  • Page ID
    55650
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    Statement

    The if statement is very simple. The general syntax is given by

    if logical expression_1

    BLOCK 1

    elseif logical expression _2

    BLOCK 2

    else

    BLOCK 3

    end

    which is interpreted by Matlab as follows:

    if logical expression 1 evaluates to true, execute BLOCK 1 and go to end (and continue on with the next line in the program);

    if logical expression 1 evaluates to false, but logical expression 2 evaluates to true, execute BLOCK 2 and go to end (and continue);

    if logical expression 1 is false and logical expression 2 is false, execute BLOCK 3 and go to end (and continue).

    Note several variants are possible: we may include multiple elseif statements between the BLOCK 1 and else; and we may omit the else and BLOCK 3 statements.

    In the event that in fact there are many cases there is another Matlab statement which is no doubt preferable to the if statement: the switch statement. We do not discuss the switch statement here, but rather use this opportunity to recall the very helpful help function: >> help switch will provide you with a quick (but sufficient) description of the syntax and functionality of the switch statement.

    while Statement

    The syntax of the while statement is

    initialize var 1, var 2,. . .

    while relational or logical expression while (var 1, var 2,. . . )

    BLOCK % new values assigned to var 1, var 2, ...

    end

    This statement is a loop which is controlled by the value of the logical variable which is the result of evaluation of relational_or_logical_expression_while. What makes the statement powerful is that relational_or_logical_expression_while may depend on var 1, var 2, . . . , the values of which are changed at each pass through the loop. In particular, the while is executed as follows: if relational or logical expression while (var 1, var 2, . . . ) is true, execute (the instruction lines in) BLOCK, otherwise go to end and continue with next line of program of which the while is part; repeat. Note that var 1, var 2, . . . must be initialized prior to entering the while loop

    As an example, we consider

    >> i = 0;
    >> sum_of_integers = 0;
    >> while i <= 3
            sum_of_integers = sum_of_integers + i;
            i = i + 1;
        end
    >> sum
    sum_of_integers =
        6
    >>  
    

    Here, relational or logical expression while (var 1) is the simple expression i <= 3, where i plays the role of var 1. In fact, this particular sum is more easily performed with a for statement, as we describe shortly. The true value of the while is when the relational or logical expression is a more complicated function of the variables which are changed by the BLOCK and in particular when we do not know a priori how many iterations through the loop will be required.

    For example, we create the script machine eps.m

    % script to calculate machine epsilon
    mach_eps = 1;
    while (1 + mach_eps ~= 1)
        mach_eps = mach_eps/2.;
    end
    mach_eps
    

    in the editor. Note that as we start to construct slightly longer programs we will start to use script mode rather than command-line mode. The input is easier, as are debugging and modification, and of course re-use. In addition, the editor within Matlab recognizes various keywords and automatically formats statements for improved readability. Note also the comment line: any material on a line which follows a % will be ignored by the interpreter and serves only to educate the author and user’s as to the intent of the program or particular lines of the program.

    We then enter in the command window

    >> machine_eps
    mach_eps =
        1.1102e-16
    >>
    

    which runs our script. Of course this code is just calculating for us machine precision, which agrees with the Matlab eps to within the factor of two related to our stopping tolerance.

    Finally, we note that you may include a break in a BLOCK statement

    if (relational or logical expression break) break

    which will directly go to the end statement of the while loop quite independent of whether relational_or_logical_expression_while (for the current values of var 1, var 2, . . .) is true or false. Purists often try to avoid break statements, but pragmatists tolerate the occasional break statement. Too many break statements may be a symptom of poor program design or more generally passive-aggressive tendencies.

    Statement

    The syntax for the for statement is

    for VARCOUNTER = LIM 1 : INCREMENT : LIM 2

    BLOCK % no reassignment of VARCOUNTER

    end

    Typically LIM_1, INCREMENT, LIM_2 would be integers (even if of data type double), however there are also many instances in which these variables could be (mathematically) non-integer. Note also that INCREMENT can be positive or negative, and that if INCREMENT is not specified then MATLAB chooses the default value INCREMENT \(=1\).

    The execution of the for loop is simple: we execute BLOCK for VARCOUNTER = LIM_1; we update VARCOUNTER = VARCOUNTER + INCREMENT; then, if VARCOUNTER \(<=\) LIM_ 2 , repeat. As for a while statement, we can interrupt the usual flow of the for loop with a break statement. Note that if \(L I M_{-} 1+\) INCREMENT is less than \(L I M_{-} 2\) then BLOCK will never be executed.

    We repeat our earlier example:

    >> sum_of_integers = 0;
    >> for i = 1:3
        sum_of_integers = sum_of_integers + 1;
       end
    >> sum_of_integers
    
    sum_of_integers = 
        3
    >>
    

    There are many situations in numerical methods in which the for loop is the ideal construct. However, it is also true that in MATLAB there are a number of functions related to array manipulation that, although implicitly built upon a for construction, are typically more efficient than an explicit for loop. We introduce some of these functions in the next section.

    Finally, we note that our for syntax here is not as general as provided for by MATLAB . However, the more general syntax requires the notions of single-index or multi-index arrays, which we have not yet introduced. Following the treatment of arrays the reader should do \(\gg>\) help for to understand the generalization: in effect, we can require VARCOUNTER to cycle through any particular set of scalars (defined in a single-index array) or VARCOUNTER itself may even be a single-index array which cycles through a particular set of single-index arrays (defined in a doubleindex array).


    This page titled 4.8: Flow Control is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Masayuki Yano, James Douglass Penn, George Konidaris, & Anthony T Patera (MIT OpenCourseWare) via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.