MATLAB Module 5: Conditional Statements and Loops
Conditional Statements
Uses of the if-end Construct
- The
if-enddecision construct is used to decide whether to execute a sequence of commands based on relational operations. - Uses:
- Displaying messages.
- Preventing undesired operations, such as skipping
log(x)for . MATLAB can handle the log of a negative number as a complex number.
Basic if-end Construct
Form:
if comparison action endKeywords:
ifandendExecution:
- If the
comparisonis true, theactionis executed. - If the
comparisonis false, the program skips to theendstatement.
- If the
Example 1
Example:
if b^2 - 4*a*c > 0 x1 = -(b + sqrt(b^2 - 4*a*c))/(2*a) x2 = -(b - sqrt(b^2 - 4*a*c))/(2*a) end
if-end Constructs with Arrays
- When the
comparisonincludes an array, all elements are compared. - An
ifconstruct requires all elements to be true for the action to be executed. - If some elements are false, the program skips to
end.
elseif
The
elseifkeyword is optional.It is useful when multiple comparisons need to be tested.
Example:
if grade >= 85 fprintf('HD\n'); elseif grade >= 75 fprintf('D\n'); elseif grade >= 65 fprintf('C\n'); elseif grade >= 50 fprintf('P\n'); elseif grade < 50 fprintf('F\n'); endThe first
elseifstatement that is true will be executed, and the others are ignored.
else
- The
elsecommand is an optional keyword in anif-endconstruct. - When the
ifcomparison is false, commands afterelseare executed. - There can only be one
elsekeyword.
Switch-Case Keywords
- Keywords:
switchcaseotherwiseend
switchis followed by a switch expression/variable (user choice).- The switch expression must be a scalar number or string.
caseallows adding statements based on a choice.otherwiseis an optional keyword and functions like theelsekeyword in anif-endstructure.
Structure of switch/case
Structure:
switch variable/switch expression case option1 code to be executed if variable is exactly equal to option1 case option2 code to be executed if variable is exactly equal to option2 case option_n code to be executed if variable is exactly equal to option_n otherwise code to be executed if variable is not equal to any of the options end
Switch-Case Construct
- This is a decision construct that is an alternative to the
if-endstructure. - The code is generally easier to read.
- Allows choosing between multiple outcomes based on a criterion, which must be exactly true.
When to Use switch/case
- The criterion can be a scalar (a number), a string, or a character.
- In practice, it is used more with strings than with numbers.
Example: Fuel Price Determination
- Suppose you want to determine the fuel price based on fuel type.
- Available fuel types:
- Ethanol 94 (E94)
- Ethanol 105 (E105)
- Unleaded 91 (U91)
- Premium 95 (U95)
- Premium 98 (U98)
- Diesel (DL)
- Premium Diesel (PDL)
if-end Approach
Example:
code = input('Enter fuel type code :','s') if strcmp(code,'E94') price = 118.9; elseif strcmp(code,'E105') price = 128.9; elseif strcmp(code, 'U91') price = 121.9; elseif strcmp(code ,'U95') price = 131.9; elseif strcmp(code,'U98') price = 138.9; elseif strcmp(code,'DL') price = 131.9; elseif strcmp(code,'PDL') price = 137.9; else price = nan; end if ~isnan(price) disp(['Fuel price for ',code,' is ',num2str(price)]); else disp(['Unknown fuel type ',code]); end
switch-case Approach
Example:
code = input('Enter fuel type code :','s') switch code case 'E94' price = 118.9; case 'E105' price = 128.9; case 'U91' price = 121.9; case 'U95' price = 131.9; case 'U98' price = 138.9; case 'DL' price = 131.9; case 'PDL' price = 137.9; otherwise price = nan; end if ~isnan(price) disp(['Fuel price for ',code,' is ', num2str(price)]); else disp(['Unknown fuel type ',code]); end
For Loops
Repetition Structures
- 'Loops' are used to repeat a set of instructions multiple times.
- MATLAB supports two types of loops:
forloopswhileloops
Concept of the for Loop
- The
forloop is a MATLAB construct that allows a sequence of MATLAB statements to be executed more than once. - The
forloop repeats a block of commands for a specified number of times; the specified number is established before the loop is executed.
Construction of for Loops
The
forloop construct:for index = [range of values in array format] command #1 command #2 command #3 ... endThe loop is executed once for each element of the index matrix identified in the first line.
for Loop Example 1
Example:
% for loop example 1 for k=[1 2 7 10] k endA 4-element array is the index array.
Displays
kin each iteration.
for Loop Example 2
Example:
for n = 1:5 fprintf('The value of n is now %d\n',n); endNote: Change the steps
n = 1:5ton = 1:0.5:5and execute the script to show thatndoes not have to be an integer.Output:
The value of n is now 1 The value of n is now 2 The value of n is now 3 The value of n is now 4 The value of n is now 5
Exercise
vector_1contains the values ofn, i.e.:vector_1 = [1 2 3 4 5]vector_2contains the squares ofn, i.e.:vector_2 = [1 4 9 16 25]You can use a loop to define, element by element, a vector; this illustrates how a
forloop works.Example:
for n=1:5 fprintf('The value of n is now %d\n' ,n); vector_1(n)=n; vector_2(n)=n^2; end
Let us create a conversion chart
- Degrees-to-Radians
- Create a table that converts angles from degrees to radians, from 0 to 360 degrees in increments of 10 degrees.
- Inputs and Outputs
- Input: Define an array of angles in degrees.
- Output: Display a table of angles in degrees and the corresponding values in radians.
The conversion table code
Code:
fprintf('Degrees to Radians \n') fprintf('Degrees Radians \n') for degrees = 0:10:360 radians = (pi./180).* (degrees); fprintf('%8.0f %8.2f \n', degrees, radians) end % the function deg2rad() can be used instead
Exercise
- Create a table that illustrates the relationship between temperature in degrees Celsius and the corresponding temperature in degrees Fahrenheit, from -40 to 100 degrees C in increments of 5 degrees. The conversion formula is as follows:
- Check the temperatures that we all may know the conversion, e.g., 0 C = 32 F, and 100 C = 212 F.
- The conversion formula is:
While Loops
Concept of while loops
- Recall from previous lectures, loops are MATLAB constructs that allow a sequence of MATLAB commands to be executed more than once.
- A
whileloop repeats a block of commands as long as an expression controlling it is true (logical 1).
The while loop construct
Construction of a
whileloop:while condition command #1 command #2 command #3 … endThe loop ends when the condition is false (logical 0); code block is repeated while condition is true (logical 1).
A while loop example
One way of controlling the loop is to define a counting index; in this case we start with
n = 0.After the
whilekeyword, an expression is defined that allows the loop to execute as long as the expression is true; in this case the loop runs untiln > 5.The counter must, of course, be changed in the loop, or the loop will run forever (infinite loop). In this case
nis increased by 1 each time the block of commands in the loop is executed.Example:
n = 0; while n <= 5 fprintf('The value of n is now %d\n'); n = n+1; end
Another Example
A program to sum a series of numbers input by a user:
a = 1; n = 0; myTotal = 0.0; while a >= 0 a = input('Enter a number to add to the running ... total (neg # to end): '); if a>=0 myTotal = myTotal + a; n = n + 1; end end fprintf('The sum of the %d numbers you input is . . . %12.3f\n',n,myTotal); % Note that the if >= 0 and end statements are needed in % this example.
User input validation
- In this example we want to ensure that the user inputs data in the correct range:
- This loop will repeat until the user has entered a non-negative number ()
Exercise
Write MATLAB code that calculates the factorial of a number using a
whileloop.a = 1; count = 1; while count < x count = count + 1; a = a * count; end output = a;
Break and Continue
- Are optional keywords in
forloops andwhileloops breakcauses the loop to terminate prematurelycontinuecauses MATLAB to skip a pass through the loop, but continue on until the criteria for ending is met- Both are used typically in conjunction with an
ifstatement
Example - Continue
Determine the sum:
total = 0; for n=1:10 if n==4 continue end total = total + n*(n^2+1)/4; end disp(total);
Break - Example
```matlab
while (1)
% calculations
% - store the previous result to prev_value
% - update the current value and store that in current_value
% check for the difference between the previous
% iteration and current iteration - delta
% delta = current_value - prev_value
% if the difference between the two is smaller
% than a set limit - end computations
if (delta < 0.001)
break
end
end
```