Simple Branching
Now that you have learned about logical operators and operations, you can move into changing the actions of your program while it is running, a condition called decision making or branching. This will significantly expand your ability to make your programs flexible and adaptable to differing conditions.
Using if
So far, you have learned about the data types you can use in Matlab. You have also learned about how to write a program in English or your native language, and use functional abstraction to translate the problem from English to Matlab. Finally, you have learned how to implement mathematical operations, as well as the basics of relational operators and logical statements.
Your next step is to take the data you have learned about and combine it with the relational operators and logical statements to provide your programs with the ability to take different program paths. The process is called decision making, and also often called branching with consideration for the analogy of taking different paths in the program, or selection with consideration for choosing or selecting from a number of program paths. As you know by now, a normal program starts at the beginning, and implements each statement in exactly the order it was typed into the program file; and as you learned, this is called linear progression or sequence. The program will continue this one line at a time process until either the program ends, or it runs into a branching condition.
At the point of the branching condition, the program steps may continue from that point forward, or the next program step may be in another location in the program. You have already seen a form of this when you used the functions. Your program comes to the function line, and the function is said to be "called". The effect of this call is that the program steps are transferred down to where the function is defined, and the work is done there. When the function has completed its work, the program steps pick back up at the next line under the line on which the function was called, and goes on.
The same condition will occur due to branching. Observe the following code.
x = 5;
if x > 10
%
% decision is not made here
fprintf( 'Value of x is larger than ten\n' );
%
end
% program skips the decision block and moves on
% whether decision is made or not, this code is run
fprintf( 'The variable x holds: %d\n', x );
You can see that the program would choose to jump over the "Value is larger than ten" output statement, and go on to outputting the value of x. The term "jump" is actually used in some lower level programming languages to implement this process. There is still another graphic you should look at before you go on however. This one addresses the path of the program in a simple line kind of process.
Notice that the program steps continue in order (i.e., one right after the other) until the branching process occurs. For the simple if statement, there are two things that can happen. If the if condition evaluates to true, the program will branch away from the normal set of steps (i.e., "up" as seen in the graphic above). If the if condition evaluates to false, the program will continue on its original path passing by the branching process. Also notice that for either condition, the program will return to the next steps following the decision making process. You will see some differences to this in later topics.
Now take a look at the form of a normal if statement operation. The code segment below presents the generalized format, and then the example used above.
Generalized standard form for using the if statement.
if conditional or relational statement, i.e., "truth"
action taken if conditional statement is true
end
Specific example related to the action above.
if x > 10
fprintf( 'Value is larger than ten\n' );
end
Using code block dividers (percent sign comment characters)
The above examples represent legal Matlab usage of the if statement action. However, there is a way to make this better, and to have significantly fewer errors in your program code. To keep from having a variety of different problems later on, you would be very wise to implement one absolute rule: Always use percent sign ('%') dividers before and after every if statement code block, as well as the other branching statements that will soon be introduced.
To make sense of this rule, consider the following.
It is standard practice to indent after every branching condition test. This is shown in the two examples above. However, the Matlab programming language has made it possible to implement more than one statement as part of a conditional operation. This is done by using percent sign dividers ('%'). As mentioned previously, the percent sign dividers allow a programmer to designate a segment of code as a block. There are other reasons to create blocks, but for purposes of this reference, the primary usage of blocks will be for branching operations.
Shown below is the same code segment demonstrated above, only this time using curly braces to denote the block of operations that will occur if the conditional test evaluates to true.
if x > 10
%
fprintf( 'Value is larger than ten' );
%
end
Code-wise, this is no different than the example shown above, except that it might be a little easier to read now that the action code is a little separated from the if statement, and showing more white space. However, it becomes more interesting if you have several things you want to implement after the conditional test.
Shown next is an example of multiple actions after the if test.
if x > 10
%
fprintf( 'Value is larger than 10' );
fprintf( 'This value is too large to be used' );
fprintf( 'x will be reset to 10' );
x = 10;
%
end
Using the dividers as shown makes it very clear where the decision has been made, and what statements will be implemented if the conditional expression evaluates to true.; Matlab enhances this with an end keyword at the end of the if statement as well. As mentioned earlier, additional white space, the space between the letters horizontally and vertically means absolutely nothing to the Matlab environment, but it could mean the difference between clarity and confusion in your program.
Designing if statement operations
After having read about the concepts of decision making and branching, this is the first topic that puts you into the coding operations. As you have seen, this is not terribly difficult. However, branching can become complicated if you do not take the time to think through the logic.
When you are designing a decision-making operation (i.e., working through your Six Step Programming Process), always separate the decision making itself from the branched operation. For example, in designing the operation mentioned earlier in this topic, consider the following.
% check for input value greater than 10
% display error message
% reset value to 10
As you can see, the decision-making action is on its own unique line, and the steps in the branched block are indented and placed independently on their own lines below. This supports: 1) one design line for each line of code, which is preferred, and 2) clarity as to which operations are the result of which decision-making processes.
Consider the following.
% if input value greater than 10, display error message and reset value to 10
While the text is reasonably clear here, you will not have the clear indication of which code operation goes on which line when you get to your coding step(s). Also, without the indenting, your design does not show any of the structure it should for decision-making operations, and clarity will probably be lost.
Wrapping up the simple action
The if statement is the easiest and simplest way to branch to the varying tasks in your program with dependence on the program data or conditions. While the if operation itself will never get more complicated, creating alternatives for the original test and actions will get a little more messy. This is not a problem as long as you use the design process first before you worry about what the code looks like. You will continue on to other topics after this one to see how that can work.
Watch this video for an overview of several of the concepts in this topic. There are also opportunities to follow along and write your own code.
Legal Stuff. All contents of this page copyright © 2003-2017 by Michael E. Leverington dba Ed Tech - Tech Ed. Other than copying or downloading code segments required for study, no parts of this page, separately or together, may be duplicated or used outside this web page without written permission from Michael E. Leverington.