Difference between revisions of "MATLAB:Selective Structures"

From PrattWiki
Jump to navigation Jump to search
m
m
Line 24: Line 24:
 
The most commonly used selective structure is the <code>if...elseif...else...end</code> structure.   
 
The most commonly used selective structure is the <code>if...elseif...else...end</code> structure.   
 
Every structure of this type at least starts
 
Every structure of this type at least starts
with an <code>if</code> statement and ends with the <code>end</code> command.  '''Important note''' - when selective structures process logic, they assume something is true ''only'' if every element in a matrix is nonzero.  For exampl
+
with an <code>if</code> statement and ends with the <code>end</code> command.  '''Important note''' - when selective structures process logic, they assume something is true ''only'' if every element in a matrix is nonzero.  For example
  
 
=== Single option: <code>if...end</code> ===
 
=== Single option: <code>if...end</code> ===
Line 145: Line 145:
 
</source>
 
</source>
 
will end up stating <code>Something in A is one or smaller</code>.  The reason for this is that the relational operation <code>[1 2 3 4 5]>1</code> produces the logical matrix <code>[0 1 1 1 1]</code> - meaning there is at least one entry that is false and so the whole thing is false.  Notice also that the <code>if</code> tree will '''not''' loop through each of the five entries but rather is asking all five questions simultaneously and reacting to the five questions at once.  If you want to get different answers for '''each''' element, you will need to either run a loop or use a [[MATLAB:Logical Masks|logical mask]].
 
will end up stating <code>Something in A is one or smaller</code>.  The reason for this is that the relational operation <code>[1 2 3 4 5]>1</code> produces the logical matrix <code>[0 1 1 1 1]</code> - meaning there is at least one entry that is false and so the whole thing is false.  Notice also that the <code>if</code> tree will '''not''' loop through each of the five entries but rather is asking all five questions simultaneously and reacting to the five questions at once.  If you want to get different answers for '''each''' element, you will need to either run a loop or use a [[MATLAB:Logical Masks|logical mask]].
 
 
 
  
 
== Questions ==
 
== Questions ==

Revision as of 02:04, 17 September 2009

Often in solving engineering problems you will have to make choices based on a set of input parameters or calculations. For example, if you are writing a program that has any kind of menu, you will need to have some kind of programming structure that will perform one of several possible functions based on user input. You may also have equations that are only relevant over a certain range of inputs and need to have a programming structure in place that will let the user know if he or she is trying to use a function for invalid inputs.

Logical and Relational Operators

There are two kinds of operator you need to learn in order to properly use selective structures. These are the relational operators (which compare two items) and the logical operators (which link or invert relational operators). Note especially that the "is equal to" relational operator is formed using two equals signs in a row.

The output from a relational operator will either be true (1) or false (0). The same is true for logical operators. Note that operator precedence is very important with respect to relational and logical operators; using parentheses to clearly establish priority will save you a great deal of time in debugging code.

if Structures

The most commonly used selective structure is the if...elseif...else...end structure. Every structure of this type at least starts with an if statement and ends with the end command. Important note - when selective structures process logic, they assume something is true only if every element in a matrix is nonzero. For example

Single option: if...end

For example, if you have code that is determining whether someone can see an R-rated film by themselves, you may want to take that person's age, compare it to the required age using a relational operator, and print a statement based on the result of that comparison. That is:

Age = input('How old is the person?');
if Age < 17
     fprintf('You may not see an R-rated movie alone\n');
end;

You can ask multiple independent questions by using several trees in a series. For example,

Age = input('How old is the person? ');
if Age < 17
     fprintf('You may not see an R-rated movie alone\n');
end;

if Age < 13
     fprintf('You should not see a PG 13-rated movie alone\n');
end;

If Age is 17 or greater, the first tree will not run and the second tree will not run. If age is less than 17 but 13 or larger, the first tree will run and the second one will not. If age is less than 13, the first tree will run as will the second. Note, however, that these trees are independent.

Default case: if...else...end

Another version of an if tree involves an "either-or" choice - either the logic is true and the first set of code will run or else the second block of code will run. For example, if you want to know if a person is old enough to legally vote in North Carolina - either they are 18 or over and they can or else they cannot. The decision tree for this might be:

Age = input('How old is the person? ');
if Age >= 18
     fprintf('You may vote!\n')
     fprintf('Be sure to register!!\n')
else
     fprintf('Can''t vote yet...\n')
     fprintf('Alas...\n')
end

MATLAB will definitely run one of the two branches of this code - the first one if the person is 18 or older, and the second one if not.


Mutually Exclusive Options: if...elseif...elseif...else...end

Sometimes, there will be several mutually exclusive options within your program. For these times you can use one or more elseif statements and possibly a closing else statement. Your program will look at the initial if statement, and if its controlling logic is false then it will start looking at the logic for successive elseif statements until

  1. it finds one that is true,
  2. it finds an else statement, or
  3. it finds an end statement.

Once the logic in a part of the structure is found to be true, or an else statement is found, or an end statement is reached, whatever code is inside that particular statement is run and then the whole if...elseif...else structure is finished - MATLAB skips over any remaining elseif or else statements. Look at the following example:

if Age < 17
     fprintf('You may not see an R rated movie alone\n');
     fprintf('You may not see an NC-17 rated movie\n');
elseif Age == 17
     fprintf('You may see an R rated movie alone\n');
     fprintf('You may not see an NC-17 rated movie\n');
else
     fprintf('You may see R and NC-17 rated movies\n');
end

Nested Decision Trees

Another more complex way of using selective structures is by nesting them. You can put selective structures within one another in order to refine the selection process based on different variables. For example, first year Duke students can go to the Math Department's page on Placement Information for First-Year Students[1] to get guidance as to what math course to take. There are several variables that enter into the placement algorithm. A possible selective structure for determining mathematics placement based purely on AP scores might be:

APtest=input('Did you take AP Calculus? (y or n): ', 's');
if strcmp(APtest, 'y')
     AB = input('What was your AB score? (0 if not taken): ');
     BC = input('What was your BC score? (0 if not taken): ');
     if BC>=4
          fprintf('You receive credit for MTH 31 and MTH 32.\n')
     elseif BC==3 | AB==5
          fprintf('You receive credit for MTH 31.\n')
     else
         fprintf('No credit based on AP scores.\n');
         fprintf('See SFI for more information.\n')
     end
else
     fprintf('See the SFI for placement information.\n')
end

Note the use of both nested selective structures and the use of compound relational operators (that is, relational operators joined by logical operators). The use of indentation helps clarify the structure, and MATLAB's built-in m-file editing program will not only do this for you but will also colorize your programs for easier parsing.

Asking Multiple Questions

When selective structure process logic, the logical questions may have more than one entry. In these cases, something is considered "true" if and only if every element in the resulting matrix is non-zero; a single "0" or false in the matrix and the entire logical question is considered false. For example:

A = [1 2 3 4 5]

if A>1
     fprintf('All of A is more than one\n')
else
     fprintf('Something in A is one or smaller\n')
end

will end up stating Something in A is one or smaller. The reason for this is that the relational operation [1 2 3 4 5]>1 produces the logical matrix [0 1 1 1 1] - meaning there is at least one entry that is false and so the whole thing is false. Notice also that the if tree will not loop through each of the five entries but rather is asking all five questions simultaneously and reacting to the five questions at once. If you want to get different answers for each element, you will need to either run a loop or use a logical mask.

Questions

Post your questions by editing the discussion page of this article. Edit the page, then scroll to the bottom and add a question by putting in the characters *{{Q}}, followed by your question and finally your signature (with four tildes, i.e. ~~~~). Using the {{Q}} will automatically put the page in the category of pages with questions - other editors hoping to help out can then go to that category page to see where the questions are. See the page for Template:Q for details and examples.

External Links

References

  1. Math Placement - Duke Math Department