Wichita State University Logo

Math 451: Computational Mathematics

2.3 Conditional Structures


2.3.1 Conditional Structures

Conditional structures allow the state of the workspace to determine the flow of control in a function. The basic arithmetic conditional statement executes an associated code block only if the expression or condition evaluates to true . If the the condition evaluates to false , then the conditional structure passes control to the next code block defined by the structure or after the end of the structure.

Basic Conditional Flowchart

Figure 1

Thus, the code block in the body of the conditional structure is executed only when the value of the expression in the condition statement resolves to true when the statement executes. This means that one will not know whether the code block of the condition structure will execute when writing the function. The state of the variables in the workspace will determine the value of the expression at runtime . When the condition resolves to true during execution we say that the condition is satisfied and the code block is executed. When the condition resolves to false during execution we say that the condition was not satisfied and the code block is skipped.

2.3.2 Nested Conditional Structures

A conditional structure may contain more than one conditional statement ! A MATLAB conditional statement may utilize the elseif keyword or else keyword to supply the MATLAB interpreter with additional conditional code blocks. The elseif statement also requires a logical expression to determine the flow of execution of the conditional structure. An else statement has no expression and always executes its code block.

On the code block following the first true condition will be executed. All other code blocks will be skipped.

The flowchart

Nested Conditional Flowchart

Figure 2

emphasizes that the algorithm consists of three mutually exclusive code blocks.

% Inputs should be numbers only
    if ~all(isnumeric([a b c]))
        error('%s: %s. %s', ...
              'Error', 'Invalid expression', ...
              'The input values must be real scalars.')

    % Inputs should be real numbers (no complex polynomials!)
    elseif ~all(isreal([a b c]))
        error('%s: %s. %s', ...
              'Error', 'Invalid expression', ...
              'The input values must be real valued.')

    % Compute the two roots
    else
        if abs(a) > eps
            % Compute the discriminant once because it is required to
            % determine both roots.
            discriminant = sqrt(b^2 - 4*a*c);

            % Calculate the two roots and assign the values to the vector x
            x = (-b + [ discriminant; -discriminant ])./(2*a);
        end
    end


  • A code block that executes when the argument list contains non-numeric values
  • A code block that executes when the argument list contains complex values
  • A code block that computes the roots of a valid real-valued quadratic polynomial
  • The else block executes only if the if block and elseif conditional expressions are false .

2.3.3 Complex Nested Conditional Structures

It is possible to include a conditional structure in any code block.

Complex Nested Conditional Flowchart

Figure 3

In MATLAB this would look similar to the following:

if (size(object) > BreadBoxSize) 
    if (size(object) > ToyotaCarolaSize)
        disp('The object is an airplane!')
    else
        disp('The object is a motorcycle!')
    end
else
    if (size(object) > ShotGlassSize
        disp('The object is a laptop!')
    else
        disp('The object is a smart watch!')
    end
end

2.3.4 Combining Several Conditions

One may combine several conditional statements into one large conditional structure.

Several Nested Conditional Statements in a Single Conditional Structure

Figure 4

In MATLAB this would look similar to the following:

type = input('Animal, Mineral, or Vegetable?')

if strcmpi(type, 'Animal')
    % Now we must guess animals

elseif strcmpi(type, 'Vegetable')
    % Now we must guess vegetables

elseif strcmpi(type, 'Mineral')
    % Now we must guess metal objects!

else
    disp('Object must be animal, vegetable, or mineral!')
end
  • the structure always starts with the if keyword and terminates with the end keyword.
  • In the source code example there is a else-block that will only be executed if all of the previous conditional expressions are false .
  • The conditional structure will only execute at most one condition block.

2.3.5 The Switch Structure

When several conditional expressions test the same variable or value to determine the correct code block, one may use a switch structure. A switch structure evaluates a single expression and chooses one of several code blocks by testing the value in a conditional expression.

Switch Flowchart

Figure 5

The MATLAB source code for a switch structure is similar to the following:

type = input('Animal, Mineral, or Vegetable?')
type = char(lower(type));

switch type
    case 'animal'
        % Now we must guess animals

    case 'vegetable'
        % Now we must guess vegetables

    case 'mineral'
        % Now we must guess metal objects!

    otherwise
        disp('Object must be animal, vegetable, or mineral!')
end

Notice that you need to convert your string to lower case and to a character array in case the user inputs a string "MINERAL" instead of a character array 'vegetable' .

2.3.6 A Complex Switch Structure

It is possible to create a MATLAB switch structure that performs dissimilar comparisons upon a value. Consider our quadraticformula example.

Instead of using Nested if structures consider the following switch structure:

% variable p contains a 1xn array of coefficients for a polynomial of degree n-1

switch true
    case ~isnumeric(p)
        error('%s: %s. %s', 'Error', 'Invalid expression', ...
              'The input values must be real scalars.')

    case ~isreal(p)
        error('%s: %s. %s', 'Error', 'Invalid expression', ...
              'The input values must be real valued.')

    case length(p)~=3
        error('%s: %s. %s', 'Error', 'Invalid Array Size', ...
              'There degree of the polynomial must be two.')

    otherwise
        % compute roots of quadratic polynomial
end

This is the type of implementation we are trying to achieve. The algorithm is clear from the structure of the source code. The switch structure communicates the purpose of each code block. This clarifies writing, reading, supporting the source code.

2.3.7 Improve the Function quadraticformula.m

First create a flowchart and then create the M-file quadraticformula2.m that implements the following:

  1. Write a new function quadraticformula2 that improves upon quadraticformula.m .

  2. Implement the nested conditions as a complex switch structure, and add a check for the length of the polynomial.

  3. Use 2.2.8 and 2.2.9. Compute the root with the largest absolute value first, and then use multiplication instead of addition to determine the second root.

  4. Compress your flowchart document and your M-file into a single file and submit it in Blackboard.

  5. Your instructor will run your M-file quadraticformula2.m using randomly generated data and check to make sure it creates the appropriate response for both valid and invalid inputs.

Creative Commons Logo - White


Your use of this self-initiated mediated course material is subject to our Creative Commons License .


Creative Commons Attribution-NonCommercial-ShareAlike 4.0

Creative Commons Logo - Black
Attribution
You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.

Creative Commons Logo - Black
Noncommercial
You may not use the material for commercial purposes.

Creative Commons Logo - Black
Share Alike
You are free to share, copy and redistribute the material in any medium or format. If you adapt, remix, transform, or build upon the material, you must distribute your contributions under the same license as the original.