If Statement

From CDS 130

Jump to: navigation, search

Contents

  1. Objectives
  2. Motivation
  3. Priming questions
  4. Notes
    1. Basic Structure
    2. Basic Structure cont.
    3. Tests
    4. Example I
    5. Example II
    6. Example III
    7. Example IV
    8. Example VI
    9. Example VII
  5. Questions
    1. Predict the output
    2. Checking Matrix Values
    3. Modifying Matrix Elements I
    4. Modifying Matrix Elements II
    5. Modifying Matrix Elements III
    6. Replacement in an array
    7. Replacement in a matrix
  6. Activities
    1. Interpreting an if statement
    2. Predicting Output
  7. Tutorial

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 a statement about population change could be "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.".

3. Priming questions

  • Think of a process that you can describe with If a condition is true, something happens, Else another thing happens.

4. Notes

4.1. Basic Structure

if (test)
  Execute these commands
else
  Execute these commands
end
  • Means if the statement of test is correct (true) then execute the commands between the if and else. If not, execute the commands between else and end.

4.2. 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.3. 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.4. Example I

  • What do you expect to happen if you execute this?
x = -1;
if (x < 3)
  x = 0;
else
  x = 10;
end
x
  • Answer: first x was assigned the value of -1. Then it was assigned the value of 0.

4.5. 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
  • Answer: The 1st element of the array A was assigned the value of -1. Then it was assigned the value of 0.

4.6. 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
  • Answer: A(1) will still be -1 and x will be 0.

4.7. Example IV

What do you expect to happen if you execute this?

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

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

end

4.8. 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.9. 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

5. Questions

5.1. Predict the output

a = 1;
if (a == 1)
 b = 2;
 if (b == 2)
    c = 3;
 end
end
c
M(10,10)= 0;
counter = 37;
if (M(10,10) == 1)
 counter = 1;
end
counter
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.

5.2. Checking Matrix Values

Consider the following program (from Nested_For_Loops#Questions) 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 program, 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 in Matlab or Octave, the first code followed by the second code, and report the value of counter that is printed to the screen.

5.3. Modifying Matrix Elements I

Using a text editor, open a new file named ifprobI.m and enter

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

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

Save your program and issue the commands :

clear
clc
ifprobI

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

Report the value of counter that is printed to the screen.

5.4. Modifying Matrix Elements II

Using a text editor, open a new file named ifprobII.m and enter

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

Below this, rewrite a version of the above that detects those positions in the M matrix that have values that are exactly equal to 0. If such a value is detected, reassign that position's value to -100. Report the value of counter that's printed to the screen. What MUST be the MINIMUM value of counter that's printed to the screen, and why?

5.5. Modifying Matrix Elements III

Open a new file named ifprobIII.m and use a nested for loop to create a 500x500 matrix that contains values in each cell according to

(j-3)^3/(i+1)^2

where j is the column number and i is the row number.

Write another nested for loop that steps through each position of the M and counts the number of times a position holds a value that is less than or equal to 0.0. Execute the program using

clear
clc
ifprobIII

and report the number of times that a value was found to be less than or equal to 0.0.

5.6. Replacement in an array

Given an array with 5 elements that are either 0 or 1, write a program that implements the algorithm

Replace any 0 with a 1.

Modify this program so that it replaces any zero with the element number where it was found. For example, if the array was

A = [1, 1, 1, 0, 0]

the modify array should be

A = [1, 1, 1, 4, 5]

because the last two zeros were the fourth and fifth elements of the original array.

5.7. Replacement in a matrix

Given a matrix with 5 rows and 10 columns, with elements that are either 0 or 1, write a program that implements the algorithm

Replace any 0 with a 1.


6. Activities

6.1. Interpreting an if statement

On this sheet of paper, write out the matrix that will be created when this program is executed.

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

Open a new file named ifprobI.m and enter the above to check your answer.

Open a file named ifprobII.m and rewrite a version of the above that detects those positions in the M matrix that have values that are exactly equal to 0. If such a value is detected, reassign that position's value to -100. Report the value of counter that's printed to the screen.

6.2. Predicting Output

Read through the following programs and try to predict the values of M and count that will be displayed. Try running these programs after guessing what will happen when you execute them. Then make changes to the programs and try to predict the result.

6.2.1.

clear; clc;
count = 0;
M(5,5) = 0;
for i=[1:5]
  for j=[1:5]
     if (M(i,j) == 0)
        M(i,j) = -1;
        count = count+ 1;
     end
  end
end
M
count
clear; clc;
count = 0;
M(5,5) = 0;
for i=[1:5]
  for j=[1:5]
     if (i == 2)
        M(i,j) = -1;
        count = count+ 1;
     end
  end
end
M
count
clear; clc;
count = 0;
M(5,5) = 0;
for i=[1:5]
  for j=[1:5]
     if (j > i)
        M(i,j) = -1;
        count = count+ 1;
     end
  end
end
M
count

6.2.2.

Write a program with a nested for loop and one or more if statements that will produce the following output. If you have problems, write out your program in long-hand to help you figure out why you are not getting the expected answer.


   -1     0     0     0     0
    0    -1     0     0     0
    0     0    -1     0     0
    0     0     0    -1     0
    0     0     0     0    -1

6.2.3.

Write a program with a nested for loop and one or more if statements that will produce the following output. If you have problems, write out your program in long-hand to help you figure out why you are not getting the expected answer.

 -1   0   0   0   0
 -1  -1   0   0   0
 -1  -1  -1   0   0
 -1  -1  -1  -1   0
 -1  -1  -1  -1  -1

6.2.4.

Write a program with a nested for loop and one or more if statements that will produce the following output. If you have problems, write out your program in long-hand to help you figure out why you are not getting the expected answer.

  0   0   0   0   0
 -1  -1  -1  -1  -1
  0   0   0   0   0
  0   0   0   0   0
  0   0   0   0   0

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.

In the following code an IF statement is 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.

Personal tools