IF STATEMENT in MATLAB: Everything You Need to Know

118

Table of Contents (click for easy navigation)

What is an IF STATEMENT?

When it comes to computer simulations of real-world applications, the right representation of a condition is key to ensuring that the appropriate scientific and engineering models are being built. There are certain conditions which are best modelled by binary representations and are depicted by the conditional IF statement. In programming terminology, IF statements are used to state desired conditions, and provide constraints for those particular conditions.

Once the constraints have been designed, they are then compared to a current condition, and a decision made by the computer as to what the outcome should be, based on the facts. The resultant outcome is a display of information, pertaining to the directives that were supplied.

A simple example of an if statement is highlighted below:

If (x>$25) {print “Thank you for shopping with us”;}

If (x<$25) {print “ Take advantage of better deals, discounts on sales over $25”;}

This is a retail application of an IF statement pertaining to determining what is to be printed on a receipt. In the discussion below, we will delve into some scientific and engineering based applications of the IF statement, as well as outline how to perform the function, and a few extensions in MATLAB.

Introduction to IF Statements

IF statements are based on conditions, which are dictated by the programmer. Depending on the system that is being assessed, there may be a need for a simple conditional statement to be written to describe the system, or a more complex one that will facilitate the appropriate description. The general syntax for IF statements is highlighted below. For a case with multiple conditions, a generic Multiple Syntax statement that can be used to describe the system is:

 
If condition [ Then ] 
    [ statements ] 
[ ElseIf elseifcondition [ Then ] 
    [ elseifstatements ] ] 
[ Else 
    [ elsestatements ] ] 
End If
 

The system descriptions can in fact be more elaborate than indicated, but for the purposes of this tutorial, the general backbone of a multi-line syntax has been established.

For a process condition with a single condition, the IF statement would be:
 
If condition Then [ statements ] [ Else [ elsestatements ]

Dimensions of an IF Statement

From the two sets of equations above, the IF statement contains three main parts, and one auxiliary attachment. These are:

  1. The condition: This is the statement that is indicating what is to be executed by the program, depending on what variables it is detecting. The program is testing the validity of the prescribed statement, and identifying if the condition is being met.
  2. The Then Statement: This statement is an indicator of what the path that is to be taken should be, once the relevant computation comparison has been deciphered by the computer. This statement is optional in the multi-condition syntax since more than one variable is at play in the decision making process.
  3. Statements: The action that the computer should take once a condition is detected. For a binary process, there will be two conditions. For a multi-line process, there will be a series of decisions to be made, before the final condition can be determined.
  4. Else IF condition: A statement that detects whether a condition is True or False, or convertible to a binary condition that only detects two possibilities in an assessment.

As the decision tree expands, the possibilities for conditions are expansive. For the purposes of this tutorial, the focus will remain on the basic IF statement and it’s functionality in the MATLAB environment.

When do we use Single-Line/Multi-Line Syntax?

The complexity of your mathematical problem will determine when you use single-line versus multi-line syntax for your conditional IF statements. If the condition under analysis is simple: for example in the case of detecting whether or not pumps in a system are on or not, a simple line of code based on the current flow through the system would suffice.

For more complex problems such as chemical engineering processes which require multiple process conditions in order to facilitate an outcome, there will be a need for multi-line syntax to determine whether or not a process target is being met.

If Statement Function Basics: Brief Tutorial In MATLAB

With the theory outlined above, let us now look at the various possibilities for IF statement calculations in the MATLAB R2018b user environment. A fresh command page is open below. As you can see, there are various possibilities for generating and manipulating code in the user environment.The critical windows for the exercise are the command window to the right hand side of the screen. This is where the relevant code for the program will be entered. To the bottom left will be the workspace, is where the answers will be displayed.

To calculate the results of an IF statement, we will enter the relevant code into the Command Window. MALAB as a system, is versatile in conditional statement execution, and the first function that will be performed in this tutorial is a simple function for the run time for a block of code to execute.  You may enter the code…in one of two ways – either copy and paste the code below into the Command Window and modify it, or simply type what is presented below.  Once entered, the system will calculate.  The if statement text for  for a simple IF condition is highlighted in the text below:

% Generate a random number
a = randi(100, 1);

% If it is even, divide by 2
if rem(a, 2) == 0
    disp(‘a is even’)
    b = a/2;
end

Entering this command into the command window, yields the following results:

The system has two options for number possibilities A or B. Once the program assesses the conditions, the two possibilities for both numbers is displayed in the workspace window to the left, as the final answer.

Based on our previous discussion, it was identified that MATLAB has the capability to provide multiple conditional options, as indicated in the multi-line syntax outline below. Using the following example from the MATLAB work book:

if statements can include alternate choices, using the optional keywords elseif or else. For example:

a = randi(100, 1);

if a < 30
    disp(‘small’)
elseif a < 80
    disp(‘medium’)
else
    disp(‘large’)
end

This example is allowing the system to decipher whether random numbers between 1 and 100 are either small, medium or large based on the constraints that have been provided to the system. Small numbers from the condition are less than 30. Medium numbers are between 30 and 80, and large numbers are greater than 80, but less than 100. The system randomly generates numbers, and determines what the classification of the outcome should be.

Multi-syntax cases do get complex over time, and the level of sophistication in the code will evolve to match the condition. To facilitate these additional requirements of the system model, MATLAB has additional functionality such as the switch statement, that allows for comparison of variables under specific condition. The case below is an assessment of the days of the week, and converts the values to predetermined lay man’s correlations to the day. For example, once Friday or Saturday approaches, there is an indication of the weekend. This conversion is a means via which conditions can be transferred from one context to the nest.

For example:

[dayNum, dayString] = weekday(date, ‘long’, ‘en_US’);

switch dayString
   case ‘Monday’
      disp(‘Start of the work week’)
   case ‘Tuesday’
      disp(‘Day 2’)
   case ‘Wednesday’
      disp(‘Day 3’)
   case ‘Thursday’
      disp(‘Day 4’)
   case ‘Friday’
      disp(‘Last day of the work week’)
   otherwise
      disp(‘Weekend!’)
end

The display above is the final outcome of the code entry. With infinite possibilities, the IF statement is the first step in the determination of whether or not process conditions are being met. For simple systems the single line syntax will suffice, while for more complicated systems the multi-line syntax will be required in order to accurately represent the system.

Conclusion

From the computations and detailed theory and background above, it can easily be identified that MATLAB R2018b is a powerful simulation tool. The system does require specialized knowledge in order to properly code and navigate the system, and has an initially steep learning curve. Fortunately, there are plenty of support tools and tutorials such as ours that are available online, that will facilitate a smooth transition to the world of MATLAB. As gamification is on the rise, users will enjoy the challenge that the system will provide in order to help them achieve in a fun and interactive manner the means via which their systems can be modelled before actual computation. IF statement computations are ubiquitous, and they can only help us to advance science and technology. Use the tutorial above to help with your scientific and engineering needs.