Sei sulla pagina 1di 27

Basic of MATLAB

Lecture 6

Eng. Al-Hasan Al-Kuhlani

Control Flow and Operators


MATLAB is also a programming language. Like other computer programming languages, has some decision making structures for control of command execution. These decision making or control flow structures include for loops, while loops, if, and switch constructions. Control flow structures are often used in script and function M-files. In a simple program as shown in the previous lessons, the commands are executed one after the other.

Here we introduce the flow control structures that make possible to skip commands or to execute specific group of commands.
2
Eng. Al-Hasan Al-Kuhlani

Relational Operators
For more information: help ops. Relational operators:Function eq ne lt gt le ge Description Equal Not equal Less than Greater than Less than or equal Greater than or equal Relational operator == ~= < > <= >=

Eng. Al-Hasan Al-Kuhlani

Relational Operators
A relational operator compares two numbers by determining whether a comparison is true or false. Relational operators can be used to compare two arrays of the same size or to compare an array to a scalar. In the second case, the scalar is compared with all elements of the array and the result has the same size as the array.

Eng. Al-Hasan Al-Kuhlani

Relational Operators
An output variable assigned to a relational or logical expression is identified as logical that is True represented by 1 False represented by 0 What is False? false or 0 What is true? anything else Special cases: Empty string Empty matrix [] What About NaN? Not true and not false NaN if (NaN) ??? NaN's cannot be converted to logicals.
5
Eng. Al-Hasan Al-Kuhlani

Relational Operators
Examples:-

Eng. Al-Hasan Al-Kuhlani

Logical operators.
Logical operators provide a way to combine or negate relational expressions. Function Description operator - Short-circuit logical AND && - Short-circuit logical OR || and - Element-wise logical AND & or - Element-wise logical OR | not - Logical NOT ~ xor - Logical EXCLUSIVE OR any - True if any element of vector is nonzero all - True if all elements of vector are nonzero
7
Eng. Al-Hasan Al-Kuhlani

Logical operators
The precedence from highest to lowest is relational operators, followed by logical operators, &, and |. Parentheses can be used to change the precedence and should be used liberally to clarify the operations.

Eng. Al-Hasan Al-Kuhlani

Logical operators
Examples:-

Eng. Al-Hasan Al-Kuhlani

Relational and Logical Functions

10

Eng. Al-Hasan Al-Kuhlani

Flow Control
Selection statements that test the results of relational or logical functions or operators are the decision-making structures that allow the flow of command execution to be controlled. For more information: help lang . The``if...end' structures: MATLAB supports the variants of if" construct. if ... end if ... else ... end if ... elseif ... else ... End Example: reply = input('Would you like to see an echo? (y/n): ', 's'); if strcmp(reply,'y') disp(reply) Eng. Al-Hasan Al-Kuhlani 11 end

If-else-end Constructions
if (expression I) statement1a; statement1b; else statement2a; statement2b; end

if (expression I) statement1a; statement1b; elseif (expression II) statement2a; statement2b; elseif (expression III) statement3a; statement3b; else statement4a; statement4b; end
12

Eng. Al-Hasan Al-Kuhlani

if...end Structures: The if statement evaluates a logical expression and executes a group of statements when the expression is true . The optional elseif and else keywords provide for the execution of alternate groups of statements. An end keyword, which matches the if, terminates the last group of statements. The groups of statements are delineated by the four keywords no braces or brackets are involved. It should be noted that: elseif has no space between else and if(one word) no semicolon (;) is needed at the end of lines containing if, else, end the end statement is required
13
Eng. Al-Hasan Al-Kuhlani

Example (if)
Here we construct a evaluates the function: conditional statement which

Solution: If x>=0 & x<=1 f=x; Elseif x>1 & x<=2 f = 2-x; else f=0; end

14

Eng. Al-Hasan Al-Kuhlani

Switch Selection Structure


The switch selection structure provides an alternative to using the if, elseif ,and else commands. The switch statement executes groups of statements based on the value of a variable or expression. Only the first matching case is executed. The syntax is: switch expression

case test expression 1 statements case {test expression 2, test expression 3} statements otherwise statements end
15
Eng. Al-Hasan Al-Kuhlani

Switch Example 1
SwitchExample.m : switch x case 1 disp(x is 1) case {2,3,4} >>x= 5 >>SwitchExample disp(x is 2, 3 or 4) x is 5 case 5 disp(x is 5) otherwise disp(x is not 1, 2, 3, 4 or 5) end

16

Eng. Al-Hasan Al-Kuhlani

Switch Example 2
month = input(Enter first three letters of the month: ,s); month = month(1:3); % Just use the first three letters if lower(month)==feb leap = input(Is it a leap year (y/n): ,s); end switch lower(month) case {sep,apr,jun,nov} The number of days in a particular days = 30; month. 30 days to September April, June case feb and November switch lower(leap) All the rest have 31 case y Except February alone days = 29; which has 28 days clear otherwise And 29 on leap year days = 28; end otherwise days = 31; Eng. Al-Hasan Al-Kuhlani end 17

Loops
A loop is a structure that allows a group of statements to be repeated. for Loop: A for loop repeats a group of commands a fixed, predetermined number of times. A for loop has the following structure:

for variable=expression statements end


The commands between the for and end statements are executed once for every column in the expression, beginning with the first column and stepping through to the last column. At each step, known as an iteration, the appropriate column of the expression is assigned to the variable. Eng. Al-Hasan Al-Kuhlani
18

For Loop
Rules for writing and using a for loop include: 1. If the expression results in an empty matrix, the loop will not be executed. 2. If the result of the expression is a scalar, the loop will be executed once. 3. If the result of the expression is a vector, then each time through the loop, the variable will contain the next value in the vector. 4. A for loop cannot be terminated by reassigning the loop variable within the loop. 5. Upon completion of a for loop, the variable contains the last value used. 6. The colon operator can be used to define the expression using the following format

for index = initial:increment:limit


19
Eng. Al-Hasan Al-Kuhlani

For Loop
Usually, expression is a vector of the form i:s:j. A simple example of for loop is for ii=1:5 x=ii*ii end The following statements form the 5-by-5 symmetric matrix A with (i; j) element i/j for ji: n = 5; A = eye(n); for j=2:n for i=1:j-1 A(i,j)=i/j; A(j,i)=i/j; end end
20

Eng. Al-Hasan Al-Kuhlani

For Example 1
Using a for loop create a 1x10 vector where each entry is the sum of its index and the square root of the previous element (the zero element value is 0) x = zeros(1,10);

x = zeros(1,10);%Allocating memory

for i=1:10 prev_num = 0; if (i == 1) for i=1:10 x(i) = i; x(i) = i + sqrt(prev_num); else prev_num = x(i); x(i) = i + sqrt(x(i-1)); end end end

21

Eng. Al-Hasan Al-Kuhlani

For Example 2
Using for loops initiate a 3x3 matrix such that: Each entry is the sum of its subscripts square A = zeros(3,3); % Dont forget to allocate memory! for n = 1:3 for m = 1:3 A(n,m) = n^2 + m^2; end end
22

Eng. Al-Hasan Al-Kuhlani

Conditional loops
Suppose we now want to repeat a loop until a certain condition is satisfied. This is achieved by making use of the MATLAB command while , which has the syntax: x=1 while expression while x <= 10 statements... x = 3*x end end It is important to note that if the condition inside the looping is not well defined, the looping will continue indefinitely. If this happens, we can stop the execution by pressing Ctrl-C.
23
Eng. Al-Hasan Al-Kuhlani

While loop

If all elements in expression are true, the commands between the while and end statements are executed. The expression is reevaluated and if all elements are still true, the statements are executed again. If the expression is false, control skips to the statement following the end statement. The variables modified within the loop should include the variables in the expression, or the value of the expression will never change. If the expression is always true (or is a value that is nonzero), the loop becomes an infinite loop.

24

Eng. Al-Hasan Al-Kuhlani

Break, continue, and return


break immediately breaks the loop. Breaks only one loop continue jump to the next iteration. return returns control to the command line (or to the calling function).
z=1; while z<10 fprintf('NO %5.0d\n',z) for k=1:10 if k==3 continue elseif k==8 break elseif z==3 return end disp(k) end z=z+1; end
Eng. Al-Hasan Al-Kuhlani

25

Exercises
Write a script to ask the user to input the scalar values for a, b, c, and x and then returns the value of ax+ bx+ c. The program repeats this process until the user enters zero values for all four variables.
Write a user-defined function to get the maximum value of three values. Write a user-defined function that searches a matrix input argument for the element with the minimum value and returns the indices of that element.
26
Eng. Al-Hasan Al-Kuhlani

Exercises
x=input('Enter x in meter: ') disp('ft--> feet') disp('in--> inch') disp('me--> meter') disp('cm--> centimeter') disp('mm--> millimeter')
unit=input('Enter 2 char for unit you want to convert to: ')

Complete the previous script using switch control structure.


27
Eng. Al-Hasan Al-Kuhlani

Potrebbero piacerti anche