M4 Programming in MATLAB
M4: Programming in MATLAB
Define MATLAB commands to create a decision-making program and provide examples. Lesson 1: Logical operators
The operators allow to compare two numbers or variables with assigned values obtaining either True = 1 or false (false = 0).
Operator |
MATLAB EXAMPLE |
Description |
== |
A== 8 ** |
It will compare the variable A to the number 8 * * and question: Is the variable A equal to 8? |
< |
A < 8 |
Question: Is the variable A less than 8? |
> |
A > 8 |
Question: Is the variable A greater than 8? |
<= |
A <=8 |
Question: Is the variable A less than or equal to 8? |
>= |
A >= 8 |
Question: Is the variable A greater than or equal to 8? |
~= |
A ~= 8 |
Question: Is the variable A different to 8? |
& |
A >= 1 & A <= 5 * |
"and (&)", Question: Is the value of the variable A between 1 and 5 including it?, Is 1 ≤ A ≤ 5? |
| |
A < 0 | A >= 1 * |
"or", question: is the value of the variable A negative or greater than or equal to 1?, is 1 ≤ A < 0? |
Table 1. Logical conditions. Gerena, D., 2018
- In versions of MATLAB less than 14, the double symbol is required for example : A > = 1 && A <= 5, A < 0 | | A >= 1.
The symbol of |, "or" is in the capital letter on the keyboard up to the key ENTER.
- * means that the program will match the value previously assigned to variable A and compare to 8, if the value of A is different from 8 then that statement is equal to 0 because is false.
Does not mean that you assign the value of 8 to the variable A.
Lesson 1: Conditional expression
The logical operators is used by the program to decide what to do according to the data provided.
The basic syntax will be:
if (logical conditional expression)
Algorithm end
The algorithm will only run if the logical conditional expression is true.
The following program is intended to inform the user whether or not a test was passed. Let's say that in an exam office to get a license, you get the license only if you achieve 70% or more on the test. The candidate takes the test, delivers it, and the staff that corrects the test enters the value in a MATLAB program that prints for the candidate a message with the test result indicating whether or not he/or she got the license and in any case informs the percentage obtained. On a page editor we will create the program for this case allowing the user to enter data.
clc clear
disp('Licenses') disp(' ')
g = input('Enter the percent obtained: ');
name= input('Enter the name of the candidate: ','s');
if g >= 70
fprintf('\n %s, Congratulations. The license will be mailed to you. \n’,name) end
fprintf(' Obtained %g %% on the test.\n',g)
The if – end command can be expanded to extend the options. The extended command is: if – else – end.
The syntax: if (logical conditional expression)
Algorithm
else
Algorithm in case the condition is not fulfilled end
clc clear
disp('Licenses') disp(' ')
g = input('Enter the percent obtained: ');
name= input('Enter the name of the candidate: ','s');
if g >= 70
fprintf('\n %s, Congratulations. The license will be mailed to you. \n’,name) else
disp('You didn’t pass the test. Try again ’) end
fprintf(' Obtained %g %% on the test.\n',g)
Notice that the option of the else did not have logical condition, in the case that the condition of the if is not true then it will make the algorithm of the else. All the elements of the command have to be aligned. View as if-else-end are aligned when you type it in the editor screen.
On many occasions more decisive ranks are required. For this we use the expanded command of the if – elseIf – else – end. Both if and elseIf carry condition expression.
Let's show a program that will tell students the average of their grades and classify it between more than or equal 90 as A, B for averages less than 90 and greater than 80, C for minors of 80 and higher than 70 and for purposes of this example print F for a lower average of 70%. The user enters the notes as a vector.
clc
clear
v_notes = input('Enter your grades between brackets [ ] : ');
s = sum(v_notes); n = length(v_notes); P = s/n; % find the average YOU can also use the command mean (v_notes)
disp(' ') % this is to leave an empty line before printing the results
if P >= 90
N = 'A’; elseif P >=80 && P < 90
N = 'B’; elseif P >=70 && P < 80
N = 'C’; else
N = 'F’;
end
fprintf('\n\b The average of your grades is: %g %% y es de %s\n',P,N)
% fprintf starts with n\ to leave a blank line before printing
% \b is backspace, moves the writing a backward space
You can replace the commands:
s = sum(v_notas);
n = length(v_notas);
P = s/n; for :
P = mean(v_notas)
Before running the program, notice that no command is underlined in
red.
If your program have something underlined, place the cursor over the line and a message will appear indicating the error you have. For example in the case shown missing close the command with the word end.
Run the program and enter as notes a combination that you know to average more than 90 and check. Remember to enter the data as a vector. Like for example:
Enter your grades between brackets [ ] : [95 89 91 99 95 100 85 ]
Associate the decision command as if it were a cabinet with several drawers. You will decide which drawer to open, as only one drawer is allowed to open. First decide if you open the first, if you decide not to open that drawer then decide if you open the second, and so one to one in the order from top to bottom. If you decide that if you open the second one, you do as you ask for that drawer and you retire, you can no longer verify what the others contain.
So if we study our program of notes, as is the order established does not need the comparison that is set as it will not verify in the other options.
Modify the condition options in your program as shown below
if P >= 90
disp('Your average is for A') elseif P >=80
disp(' Your average is for B') elseif P >=70
disp(' Your average is for C') else
disp(' Your average is for F')
end
If the average was 84, which of the conditional cases would be true? Its logical answer should be B and C, but when analyzing each case we find that the first situation is false because P = 84 is not greater than 90 so goes to verify the second option, and in this the statement will be true, so run that algorithm and comes out, goes straight to the end, no longer checks the other options. So there is no problem with defining the third as greater than 70 without limiting it, although 84 is greater than 70, it will not reach that option because it already enters the previous option.
Run the program the number of times you need to validate the results for each option.
Example:
You are hired to create a program that calculates the payment of the employees of X company that earn tips from the clients served. Employees charge weekly at $4.00 per hour. If the tip received does not complete the equivalent of $8.00 the time in the week the company completes the payment and if you are required to work more than 40 hours in the week you pay the additional time to $10.00 without conditioning the tip. It has as data the hours worked weekly and the tips received.
Code
clc clear
D = 4; % payment per hour
Dmin = 8; % adjusting payment
De = 10; % payment for extra hours
h = input('Enter the number of hours worked in the week. Hours: ‘); tip = input('Enter the tip: '); n = input('Enter the name of the employee: ','s'); a = input('Enter the employee’s last name: ', 's');
if h <= 40
Pay = h * D + tip;
if Pay < h*Dmin % compares if the payment with the tip is less than working at $8 per hour and adjust it if is true Pay = h*Dmin;
end else
extra = h - 40;
Pay = 40 * D + extra * De + tip; if Pay < (40 * Dmin + extra * De)
Pay = 40 * Dmin + extra * De; % in case that the payment with tip
% do not exceed $8 plus $10 per hour extra
% the program adjust to that amount as minimum payment
end end
fprintf('\n The payment of %s %s will be %.2f n\',n,a,Pay)
Notice the use of the if command within another if.
Example
Write a program that finds the real roots of a quadratic equation ax² + bx +c = 0. The program will allow the user enter the coefficients a, b and c
The program will first calculate the discriminator of the equation given by:
D = b² - 4 a*c
If D is positive it'll print a message that reads: The equation has two real roots.
And the roots are calculated with R_1 ; R_2 = ;
If D equals zero, the program will print: The equation has a root.
And it'll calculate the root as R = ;
If the D is negative then it has no real roots and it'll print: The equation has no real roots.
Check the program for a) in this case a=3, b=6, c=3
Code:
clc clear
disp(‘ Find the real roots of a quadratic equation') disp('ax² + bx + c = 0') disp(' ') a = input('a = '); b = input('b = ');
c = input('c = ');
D = b^2 - 4*a *c;
fprintf('\n %g x^2 + %g x + %g = 0 \n', a, b, c) % print the equation
if D > 0
disp('The equation has two real roots')
x1 = (-b + D)/(2*a); x2 = (-b - D)/(2*a); disp(x1) disp(x2)
elseif D == 0
display('The equation has a real root') x = -b /(2*a);
disp(x)
else
disp('The equation has NO real roots') end
Run the program for the given equations. Check your answers.
Note: Use of the else is not required in all cases. It is important that you do not type condition in the else, the algorithm on else space is executed when all of the previous alternatives are false.
Lesson 3: Program representation at flowchart
A flowchart is a way to represent a program regardless of the language used. For this we use different geometric figures that represent a part of the program. Usually a program is divided into three sections, data entry, algorithm and output or printout of results. In Module 3, the figures corresponding to input and output of data were discussed. This module presents the figures corresponding to the decision command.
Example:
In the figure 2 observed the representation of the program below.
N = input('Enter the test average: ');
if N >= 70
disp(' Passed the test. The license will be mailed to you’) end
fprintf(' Your test average is: %g %%.\n',N)
Note that the flowchart does not show program details or specific formats, it shows only the essentials. Remember that the purpose is to show another programmer the algorithm. Do not confuse the end with the end of the if command. It's two different endings. The end of the flowchart indicates that the program is over.
Representing the else command in flowchart
N = input(‘Enter the test average. ');
if N >= 70
disp('L The license will be mailed to you’) else
disp('Not passed the test.’)
end
fprintf(' Percent of the test is: %g %%\n', N)
Representing the elseIf command in flowchart
v_N = input('Enter a vector grades: ');
P = mean(v_N);
if P >= 90
disp('Your average correspond to A') elseif P >=80 && P < 90
disp('Your average correspond to B') elseif P >=70 && P < 80
disp('Your average correspond to C') else
disp('Your average correspond to F') end
fprintf('\n\b Your average is: %g %% \n',P)
Note that the figures of the flowchart increases on the side of the false because if it is true then ends and does not check the other alternatives as shown in the connectors.
Assign value to a variable and define equations |
Assign value to a variable and write formulas | |
Call to subroutines or certain procedure |
Call to subroutines or functions | |
Indicates the direction of the flowchart | ||
Page or sequence connector on the same site. | ||
False |
True |
Conditional statement where |
being true performs an algorithm and if it does not perform another algorithm. |
if, elseif, else if |
Table 2: Flowchart representation. Gerena, D., 2018
Multiple Choice:
- Select the statement that filter the cases when P results more or equal than 100 a) if P >= 100
- if P >== 100
- if P > & P== 100
if P > 100
- Select the statement that filter the cases when P results negative
- if P > 0
- if P < 0
- if P > -1
- if P < -1
- Need a statement that filter the cases when P results between 3 and 5 included
- if P > 3 && < 5
- if 3 <= P <= 5
- if P <= 3 && P <= 5
- if 3 <= P && P <= 5
a, b, d
Commands: Some commands discussed in this module:
If – Else – end
If – ElseIf – else-end
rendering in flowchart
Practice
A function evaluates the growth of a new strain of influenza virus in a person's body. Develop a program that allows to determine the value of the function f(x) (hours of being infected) for a value of x entered by the user, the value of x is the degree of reaction to the virus of a blood test.
- Ask the user to enter the value of x.
x: Degree of reaction to the virus from a blood test (simulate) viral strain
- The program must decide which function is used according to the enter x value and calculate the f (x) corresponding to the number of hours infected. For any of the cases except when f (x) = 0, the program must print the value of f (x) as:
_____ hours of being infected.
If f (x) = 0, the program must print: Negative, has not been infected. ** notice that the line space correspond to the f(x) value
Practice:
Situation:
The blood bank of Puerto Rico is conducting a campaign to raise awareness of good health, which should be a program where entering the age should result in the amount in millions per milliliter of globules you should have.
For example: you enter as age 10 years, you must print: NAME must have between 4.2 to 5.2 million / ml of red blood cells.
It can be guided by the following table:
Newborns |
4 to 5 millions/ ml |
At 3 month |
3.2 to 4.8 millions/ ml |
At the first year |
3.6 to 5 millions/ ml |
Between 3 and 5 years |
4 to 5.3 millions/ ml |
From 5 to 15 years old |
4.2 to 5.2 millions/ ml |
- Your program must ask the user to enter the age
- Your program must ask the user to enter his name
- You must decide what information you will give in cases when the age entry is not directly stipulated in the table.
- For any case, the user will receive a sentence beginning with his name and the data that indicate the range in which he must have the blood cells
- Identify your work with your personal data (Name, last name, id student number).
- Copy the program code and draw the flowchart that represent the program in the same page.
For more practice refer to the textbook Gilat, A. (2015). MATLAB, An Introduction with Applications: 5th edition. Wiley Chapter 6.
Want to order fresh copy of the Sample Template Answers? online or do you need the old solutions for Sample Template, contact our customer support or talk to us to get the answers of it.