MATLAB essential/Control Flow
|This course is currently under construction for more information contact gtouchan94|
Open your MATLAB or go to this website if you do not have access to MATLAB on your PC. If you want to use the editor (script on the left) make sure to save your work using the drop-down menu before running it
This lecture is very important because what you learn here is applicable to other programming languages such as java, C, C++, and C#. While the syntax might differ between these languages, the logic is almost the same.
Relational and Logical OperatorsEdit
Below is a list of Relational Operators
|==||Returns (1) if the number or variable to its left is equal to the value or variable to its right. Returns (0) otherwise.|
|~=||Returns (1) if the number or variable to its left does not equal the value or variable to its right. Returns (0) otherwise.|
|<||Returns (1) if the number or variable to its left is smaller than the value or variable to its right. Returns (0) otherwise.|
|<=||Returns (1) if the number or variable to its left is smaller or equal to the value or variable to its right. Returns (0) otherwise.|
|>||Returns (1) if the number or variable to its left is bigger than the value or variable to its right. Returns (0) otherwise.|
|>=||Returns (1) if the number or variable to its left is bigger or equal to the value or variable to its right. Returns (0) otherwise.|
In MATLAB 1 means True and 0 means False. You can find the documentations of these operators here.
It might help you to remember if you think that you should have a smiley emoji face when you have less or equal to, and a sad emoji face when you have larger or equal to. You should remember also to put the ( = ) sigh to the right side always.
Here is a lost of Logical Operators.
|&&||and||Returns 1 ( true ) if both the expressions on it left and on its right are true. Return 0 otherwise||Input: 4 > 3 && 7>=2 . Output: 1
nput: 4 > 3 && 7<=2 . Output: 0
|||||or||Returns 1 ( true ) if only one of the expression to its or to its right are true. Returns 0 otherwise||Input: 4 < 3 || 7>=2 . Output: 1|
|~||Not||Returns 1 (true) if a certain statement is not correct. Returns 0 otherwise||Input 4~=3 . Output: 1
Input 4~>4 . Output: 0
Why used themEdit
If statements are categorized as Control Flow tools. These statements are used in order to change the segments of code that will be executed executed when one or more variable change its value.
How to use themEdit
If statements in MATLAB and object oriented programming languages has almost the same general form. This is a short an easy example of if statements. The logic behind if statements in MATLAB, could be summarized using Figure#1. If the (A) is true, then the block of code in (B) will be executed. If (A) is not true, then the block of code in C will be executed.
Consider this simple MATLAB code:
a = -2; if a > 0 disp('a is bigger than zero') else disp('a is smaller than zero') end
Code Explanation: In this code, (disp) is short for display. It is a command used to display a message. You should end each if statement with the word (end). The output in the command window will be : a is smaller than zero.
Let's consider an other example. This code is used to determine whether a player should be in the top 5, top 10, top 15, or no ranking based on the number of fouls commited, number of points scored, and number of games played.
%% prompt= 'Enter the number of fouls commited by the player '; Num_fouls=input(prompt) prompt2= 'Enter the number of points the number scored '; Num_points= input(prompt2) prompt3= 'Enter the number of games the player played '; Num_games= input(prompt3) %% A= Num_fouls <5; % returns 1 if the number of fouls is less than 5 B= Num_points > 40; % returns 1 if the number of points scored is more than 40 C= Num_games >15; % returns 1 if the number of games is more than 15 %% if (A==1 && B==1 && C==1) disp('Player should be in top 5') elseif (A==0 && B==1 && C==1) disp(' PLayer should be in top 10') elseif ( A==1 || B ==1 || C==1 ) disp(' player should be in top 15') else disp(' player should not be in any ranking') end
Code Explanation: I will explain the code line-by-line:
Line 1: a double percent sign was used to create a cell block. Review lecture 1 for more information. Line 2: A sting called (prompt) was created. Review lecture 1 to see how to create string. Line 3, a variable called ( Num_fouls ) was created. This variable determines the number of fouls committed by the player. The value of this variable is determined by an input from the user. This was made possible by using the the command input. The same procedure was repeated in lines 4,5,6,7 where two strings were created, and two variables which values are determined by the user were also created. Line 9: a new cell was created using a double percent sign. Lines 10-11-12: Relational Operators were used to compare the values entered by user (that represent the player's data) with the standard that the player should meet to be considered in the top players. If Num_fouls was less than 5, A was given the value 1 or true. If Num_points is more than 40, B=1. If Num_games is more than 15, C=1. Line 13: a new cell block starts. Line 14: if statement was used to control the flow of the code depending on the values of A, B, and C. Line 17: if the first if statement was not executed, MATLAB consider the ifelse statement in line 17. Line 20: If the ifelse statement was not executed, MATLAB considered the next ifelse statement. Lines 23-24: if neither one of the previous statements got executed, else is used to display the message in line 24. Line 25: the key word (end) is used to end the if statement. Without using this word, MATLAB will give you an error and not run the code.
Consider these Examples. Click on pictures to see full size.
The chart below explains how the code works. Click on the picture to see it full size
You may be interested in: Wikibooks_MATLAB_if_Statements
Loops are used to ask MATLAB to execute the same piece of code a specific number of times. In this lecture, two types of loops will be explained.
for c= 1:5 disp('testing') end
For documentation, Click here
Executes the statement(s) within the loop a specific number of times. In the previous short example, the statement is executed 5 times, so the word (testing) will be displayed five times. The reason for that is because every time the loop iterates, the value of c increases by 1. When the value of c reaches 5, the loop stops. To better understand this concept, see the long example below.
The code below is used to convert from meters to feet and yards using MATLAB for loop. Click on the left image below to see the code in full size. If you want to see the output of this code, go to this website and write the code.
Line by line explanation of code
Line 1 and Line 2: include comments that explain the function of the code. Line 4: Three variable were created using the word (syms). Review lecture 1 to see how create a variable. Line 7: contains the first line of the loop. In this line the programmer asks MATLAB to keep executing the statements inside the loop until the value of the variable Number_of_meters reaches 20. Keep in mind that the initial value for this variable is 10, and that this value increases by 1 each time the loop iterates. Line 8: contains the equation used to convert from meters to feet. Line 9: contains the equation used to convert from meters to yards. Line 11: a string called Conversion_to_feet was created. This string contains the command (num2str) which is used to display the value of variable in a sting. Click here to see its documentation. Inside this string the number of meters is displayed, followed by a message, and then followed by the number of feet which is contained in variable Number_of_feet. Line 12: display the string (Conversion_to_yards). This line is very similar to line 11, but the number of yards is displayed instead the number of feet. The same command (num2str) is used inside this string. Line 13: the word (end) is used to close the loop. Keep in mind that every time the loop iterates the value of Number_of_meters changes, so the values of Number_of_feet and Number_of_yards changes as well leading to a different output. The loop iterates 11 times.
Output (Click on image to see full size)
You may be interested in: 
Start=3; Finish=5; while Start<Finish disp('testing'); Start=Start+1; end
You can think of the word (while) as a short way to say (while this statement is true, execute the following statements). In the previous example, the word testing will be shown until the variable (Start) is equal to the variable (Finish). The value of variable start will increase every time the loop iterates because of the command in line 5. As a result, the word (testing) will be shown twice. When the variable Start has value of 5, the loop will not be executed because Start<Finish. If Start<=Finish, we would have a different case. Refer to the long example to better understand this loop.
To the loop's documentation, Click here
A long example:
The code below can be used to create a game where MATLAB creates a random number, and you have to keep guessing until you get that number.
Random_Num=randi([10 20 ]); prompt= 'Enter a number from 10 to 20 \n'; Number_Entered=input(prompt) if (Number_Entered~=Random_Num) while Number_Entered>Random_Num disp('The number entered is larger than the random number ') prompt= 'Enter a number from 10 to 20 \n'; Number_Entered=input(prompt) end while Number_Entered<Random_Num disp('The number entered is samller than the random number ') prompt= 'Enter a number from 10 to 20 \n'; Number_Entered=input(prompt) end disp(' Your answer is right !!') end
Explanation of code:
Line 1: the command in this line generate a random number between 10 and 20. Line 2 & 3: Create and show a string that asks the user to enter a number between 10 and 20. Line 5: contains a conditional statement. If the number entered is not equal to the random number generated by MATLAB, the program will execute one of the two while loops. If the numbered entered is equal to the random number, the program will go directly to line 18. Line 6: contains the command that checks if the number entered is bigger than the random number. The loop will keep iterating until either the number entered is bigger than the random number, or the two numbers are equal. Line 7 & 8 : tell the user that he entered the wrong number, and ask him to enter a new number. Line 9: assign the new entered number with the variable Number_Entered. Without this statement, the loop will keep iterating. Line 11: contains the command that will terminate the loop when the condition in line 6 is not met anymore. Lines 12 through 16 : are similar contain the loop that is very similar to the previous loop, with one difference that is the numbered entered is smaller than the random number. Line 18: display a message saying that the answer is correct. Line 19: end the if statement.
You may be interested in: Wikibooks_MATLAB_Loops
Turning the computer into a radiator by running an infinite loop that involves complicated equations. credit to MATLAB Answers.
Do you have a suggestion on how to improve the lecture?, Click here to send me an email.