1. Objectives

• To introduce the use of the if statement.

2. Motivation

• A fundamental part of many algorithms is: "If something is true, do this. Else, do that." For example, "If population is less than 10 billion, population next year is equal to 1.1 times the population this year. Else, the population next year is 0.1 times the population this year (disease spread)".

3. Pre-questions

• Think of a process that you can describe with If a condition is true, something happens, Else another thing happens. Bonus if it is funny and SFW.

4. Slides

4.1. Basic Structure

if (true of false question)
Answer to question true: Execute these commands
else
Answer to question false: Execute these commands
end


Means "if the answer to the question in parentheses is true, then execute the commands between the if and else; if the statement in parentheses is false, execute the commands between else and end".

4.2. Basic Structure cont.

The else is optional.

This type of logic is often needed:

if (true of false question)
Do something if answer to question is true
else
Do nothing
end


This may be re-written as:

if (true of false question)
Do something if answer to question is true
end


4.3. Basic Structure cont.

Example of a test that is incorrect, because 37 does not equal 2:

if (37 == 2)
Commands here get ignored
else
Commands here get executed
end


In this case the commands between the else and end are evaluated. The commands could be anything, like a for loop or another if statement.

4.4. Tests

Besides putting in just numbers for test, one can compare variables that hold a number. For example, if

x = 37
y = 2


then test could be anything in the second column of this table.

Meaning test syntax
is x less than y? x < y
is x greater than y? x > y
is x equal to y? x == y
is x less than or equal to y? x<=y
is x greater than or equal to y? x>=y
is x not equal to y? x ~= y

4.5. Example I

• What do you expect to happen if you execute this?
x = -1;
if (x < 3)
x = 0;
else
x = 10;
end
x


4.6. Example II

What do you expect to happen if you execute this?

A(1) = -1;
if (A(1) < 3)
A(1) = 0;
else
A(1) = 10;
end
A


4.7. Nested ifs

As with for loops, if statements may be nested. For example,

if (a == 1)
if (b == 1)
c = a+b;
end
end


will only assign c the value of a+b if both a and b are equal to one.

4.8. Example III

What do you expect to happen if you execute this?

x = -1;
A(1) = -1;
if (A(1) < 3)
x = 0;
else
x = 10;
end
A
x


4.9. Example IV

What do you expect to happen if you execute this? Work it out on paper and then enter it into MATLAB.

A = [1,2,3,4,5];
for i = [1:5]

if (A(i) > 2)
A(i) = 0;
else
A(i) = 1;
end

end


4.10. Example VI

What do you expect to happen if you execute this?

M = [ 1, 2 ; 3, 4 ];
for j = [1:2]
for i = [1:2]
M(i,j)
end
end


4.11. Example VII

What do you expect to happen if you execute this?

M = [ 1, 2 ; 3, 4 ];
for j = [1:2]
for i = [1:2]

if (M(i,j) > 2)
M(i,j) = 0;
else
M(i,j) = 1;
end

end
end


4.12. Example VIII

Consider the following code that generates an matrix M and fills its positions with values:

for i=[1:40]
for j=[1:40]
M(i,j) = (i-3)*(j+3);
end
end


Now consider the following code, which steps through each position in matrix M and checks to see if the value at a position is greater than 150. If so, that position is reassigned the new value -100, and the variable counter is incremented by one (to record the fact that we changed a value in M):

counter = 0;
for i=[1:40]
for j=[1:40]
if (M(i,j) > 150)
M(i,j) = -100;
counter = counter + 1;
end
end
end
counter


Run the above two codes, the first code followed by the second code, and report the value of counter that is printed to the screen.

5. Questions

5.1. Modifying Matrix Elements I

(5 pts)

Open a new file named ifprobI.m and enter

counter = 0;
for i=[1:5]
for j=[1:5]
M(i,j) = i*j;
if (M(i,j) > 10)
M(i,j) = -1;
counter = counter + 1;
end
end
end
counter
M


Below this, in the same file, write a nested for loop that detects the positions in M that have a value that is equal to -1. If such a value is detected, reassign its value to -2.

Save your program and issue these commands on the command line:

clear
clc
ifprobI
M


(clear deletes all existing variables and clc clears the command line window).

Post a screenshot to your wiki page that shows your program along with the output from your commands on the command line (see exampleshot, which has the wrong answer, as an example.).

5.2. Modifying Matrix Elements II

5.2.1.

(5 pts)

Write a nested for loop that creates a matrix that looks like this:

 1  2  3  4  5
6  7  8  9 10
11 12 13 14 15
16 17 18 19 20


5.2.2.

(10 pts)

Using a single if statement, modify the nested for loop so that it creates a matrix that has all zeros in the third row:

 1  2  3  4  5
6  7  8  9 10
0  0  0  0  0
16 17 18 19 20


5.2.3.

(10 pts)

Using a nested set of if statments, modify the the nested for loop so that it create a matrix that looks like this:

  1  2  3  4  5
6  7  8  9 10
11 12  0  0  0
16 17 18 19 20


6. Other Questions

These are extra problems of the type that may appear on the Final exam but were not assigned as homework. You should be able to predict the output by just reading the program.

6.1. Predict the output

A = [1,0,3,0,5,0,7,0,9,0,11,0,13];
for i = [1:13]
if(A(i) == 0)
A(i) = A(i-1);
end
end
A

A = [0,0,0,0,0,0,0,0,0,0,0,0];
for i = [2:2:12]
if(A(i) == 0)
A(i) = i-2;
end
end
A

A = [1,0,1,0,1,0,1,0,0,1,1,1];
for i = [1:12]
if(A(i) == 0)
A(i) = A(i-1);
end
end

for i = [2:2:12]
if(A(i) == 1)
A(i) = 0;
end
end
A

A = [1,0,1,0,1,0,1,0,0,1,1,1];
for i = [2:12]
if(A(i) == 0)
if(A(i-1) == 1)
A(i) = A(i-1);
end
end
end
for i = [12:-1:2]
if(A(i) == 1)
if(A(i-1) == 0)
A(i-1) == 0.5);
end
end
end
A


These questions are intended to be worked in order, as each question builds on the previous question. To answer these questions, please refer to If_Statement#Slides, your notes from class, and If_Statement#Tutorial.

7. Tutorial

By Joseph Marr (Slight modifications by Robert Weigel - Original version)

This is a short tutorial on Matlab's IF statement. The IF statement permits your program to make decisions as it runs, on the basis of conditions that may or may not be true. This is a very powerful capability for programs to have, as it enables them to detect changes that may occur during a run, and implement modifications on the basis of the detected changes. IF statements have the following basic structure (syntax):

if (test)
First statement sequence
else
Second statement sequence
end


The key here is the "test": if test evaluates TRUE, then the IF statement executes its first statement sequence. But when the test evaluates FALSE, then the IF statement executes its second statement sequence. Only one of these two statement sequences is selected for execution, never both, and the sequence that's selected will execute only once. Then the IF statement finishes its execution and the program continues processing the statements that occur after the IF statement (if any). Note that the statement sequence that IF selects for execution could consist of just one, single statement.

"Test" is a logical condition. That means we use logical operators such as "less than", "greater than" and "equal to". For example, if we wish to test whether some variable "x" is less than 3, we would write the following inside the parentheses where the word "test" appears: x < 3. Here's a short table displaying the meanings of common logical conditions, and the Matlab statement that's valid to insert into the parentheses where the word "test" appears:

Meaning of test Syntax
is x less than y? x < y
is x greater than y? x > y
is x equal to y? x == y
is x less than or equal to y? x<=y
is x greater than or equal to y? x>=y
is x not equal to y? x ~= y

Let's say that I want to test a variable x with an IF statement, as follows: If x is less than 3, then I want to set the value of x equal to 0. But if x is not less than 3, then I want to set the value of x equal to 10. The following Matlab IF statement does precisely this:

if (x < 3)
x = 0;
else
x = 10;
end


In this example, if x had previously been assigned the value of, say, -5, then after executing the IF statement, x would have the value 0 assigned to it. Similarly, if x had previously been assigned the value of, say, 176 (or any value that's not less than 3), then after executing the IF statement, x would have the value 10 assigned to it. But what if x has previously been assigned the value of 3? What happens in that case, when x equals 3?

If you answered, "x would have the value 10 assigned to it", you're right. Why? Because the test checks whether x is less than 3. And that's all that the test checks. So when x holds any value less than 3, the test evaluates TRUE, and the first statement sequence executes. But if x holds the value 3, or any value greater than 3, then the test evaluates FALSE and the second statement sequence executes.

IF statements can also be written without the second statement sequence. We would write an IF statement this way if we only wanted to take an action when the test evaluates TRUE; if the test evaluates FALSE then we don't want to do anything. The following IF statement variant handles this situation, i.e., "do something if test evaluates TRUE but do nothing if test evaluates FALSE":

if (test)
statement sequence to execute when test is true
end


Here's an example of a situation where we'd want to use this IF statement variant: Let's say that I have a 1x5 array M filled with values. I want to test each of these values in M and if any of them are less than 0, then I want the value in that exact position of the M array to be set equal to 0. Recall the tutorial on nested FOR loops [1], where we used a FOR loop to step through each of the positions of an array. Now we'll use a FOR loop and put the IF statement variant inside of it, so that we can test the value in each position of the M array:

for i = [1:5]
if (M(i) < 0)
M(i) = 0;
end
end


See how that works? We use the FOR loop to do what we already know how to do, namely, visit each position in array M and then we use the IF statement variant just discussed to test each of those positions in the M array and whenever IF detects that a position holds a value less than 0, that position is reassigned the value 0. Here's the output when I enter the above code into Matlab (I first enter an array M that contins some negative values, so that the FOR statement has an array to work on, and then after the FOR loop is done, I ask Matlab to print out the values in all of M's positions):

Entering

M = [-1,3,7,-10,5]


on the command line gives

M =
-1  3  7  -10  5


Entering on the command line

for i = [1:5]
if (M(i) < 0)
M(i) = 0;
end
end
M


gives

M =
0  3  7  0  5


The FOR loop did exactly what I wanted it to do: It reassigned the value 0 to all positions in the M array that previously held negative values, while leaving the other positions undisturbed.

This is quite a powerful capability to have. Imagine that we have a two dimensional, NxN array called P (where N is any positive integer, possibly a very large positive integer) and we want to go through P, position by position, looking for negative numbers. If we find any, we want to set the value at that position in P equal to something else---maybe 2.5, for example. Here is the Matlab code that will do this job. Notice the use of nested FOR loops, which we covered in "Short Tutorial I":

for i = [1:N]
for j = [1:N]
if (P(i,j) < 0)
P(i,j) = 2.5;
end
end
end


Wala! We've just processed the ENTIRE array P, and those positions of P that previously held negative values will now hold the value 2.5.

The above structure---namely, an IF statement embedded inside a doubly nested FOR loop---is a basic image processing tool: Using the above Matlab code, you can step through an ENTIRE two dimensional image (which is really a two dimensional array), examine each pixel in that image (pixels are nothing more than locations inside a two dimensional array that hold an integer value), and then, make decisions based on the values of the pixels examined.

For example, one could process a black-and-white image (which is just a two dimensional array, each position of which is called a "pixel") by searching for black pixels (i.e., array locations holding a particular integer value) and when found, resetting the value at that location to the integer value representing "white" (i.e., a different integer value). By doing so, we'd create a negative of the original black-and-white image!

IF statements are so common and useful in programming that it's really impossible to create substantial programs without them. Therefore, you are STRONGLY encouraged to learn how to use IF statements. This short tutorial just scratched the surface. In particular, the "test" can get quite complicated, using multiple ANDs and ORs, to create what are called "compound conditions". Compound conditions enable IF statements to do much, much more. For example, if you wanted to change the values of pixels that were inside some specified RANGE of values, you'd need to use a compound condition to define that range.

You may now want to revisit the "ears_of_corn.m" Matlab code that I distributed recently as the solution to a bonus problem. In that code, I used an IF statement embedded inside a FOR loop, to decide whether it was a sunny or cloudy month:

for i = [2:12]
sunny = rand(1);
if (sunny <= 0.80)
corn(i) = corn(i-1) + 0.125*corn(i-1) - 85;
else
corn(i) = corn(i-1) + 0.0125*corn(i-1) - 85;
end
end


This code should now be fairly easy to understand: If the random variable "sunny" is less than or equal to 0.80 (representing an 80% chance that it will be sunny), then one particular iteration equation is executed. But if not, (i.e., if "sunny" is greater than 0.80, representing the remaining 20% chance that it's cloudy instead), then a different iteration equation is executed. Each FOR iteration may therefore compute a different corn yield for the following month. If you have the time, I suggest that you re-read "ears_of_corn.m" to see how it works. Armed with your new understanding of IF statements, "ears_of_corn.m" should seem quite straightforward.