2. The IF Statement
• Logical statements are used to control the
sequence of computations in programs and in
spreadsheet
• MATLAB and Excel both contain IF statements for
adding logical control
• An IF statement tests a condition, and the flow of
calculations is dependent on whether the
condition is true or false
• This is best illustrated with a simple example
3. Logical Test Example
• Consider taking the absolute value of a number
• How would you instruct Excel to perform this
function (without using the built-in function ABS)
• There are ways to accomplish this without an IF
statement (for example, you can square the
number and then take its square root, which
always returns the positive root), but the most
straightforward method is to use a logical test
Engineering Computation: An Introduction Using MATLAB and Excel
4. Logical Test Example (cont.)
• In words, you might describe your procedure as:
“If the number is less then zero, then take the negative of
that number, else leave the number as it is”
• This if-then-else logic is widely used in
programming, and can also be used in Excel
• Format of Excel IF statement:
-if(logical_test,value_if_true,value_if_false)
Engineering Computation: An Introduction Using MATLAB and Excel
5. Excel IF Statement
• The IF statement is a function, with three arguments
• The first argument is the logical test (the condition).
For our example, the logical test will be that the value
of the number considered is less than zero
• The second argument is the action to be taken if the
condition is true (take the negative of the number)
• The third argument is the action to be taken if the
condition is false (report the input number
unchanged)
Engineering Computation: An Introduction Using MATLAB and Excel
6. Absolute Value Example
• The number to be evaluated is entered into cell A1
• The formula is entered into cell B1
Engineering Computation: An Introduction Using MATLAB and Excel
7. Nesting IF Statements
• Often, there will be more than two possible outputs for a given
input
• In MATLAB, we use the if-then-else function
• In Excel, we must nest IF statements
• Consider this example: we want to read in a numerical grade and
convert it to a letter grade on a scale of:
– Greater than or equal to 90 = A,
– Greater than or equal to 80 and less than 90 = B
– Greater than or equal to 70 and less than 80 = C
– Greater than or equal to 60 and less than 70 = D
– Less than or equal to 60 = F
Engineering Computation: An Introduction Using MATLAB and Excel