Lecture6 Eng.alhassan

download Lecture6 Eng.alhassan

of 27

Transcript of Lecture6 Eng.alhassan

  • 7/28/2019 Lecture6 Eng.alhassan

    1/27

    Basic of MATLAB

    Lecture 6

    Eng. Al-Hasan Al-Kuhlani 1

  • 7/28/2019 Lecture6 Eng.alhassan

    2/27

    Control Flow and Operators

    MATLAB is also a programming language. Like othercomputer 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.Eng. Al-Hasan Al-Kuhlani2

  • 7/28/2019 Lecture6 Eng.alhassan

    3/27

    Relational Operators

    For more information: help ops.

    Relational operators:-

    Eng. Al-Hasan Al-Kuhlani3

    Function Description Relational

    operatoreq Equal ==

    ne Not equal ~=

    lt Less than le Less than or equal =

  • 7/28/2019 Lecture6 Eng.alhassan

    4/27

    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 toa 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-Kuhlani4

  • 7/28/2019 Lecture6 Eng.alhassan

    5/27

    Relational Operators

    An output variable assigned to a relational or logicalexpression 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.

    Eng. Al-Hasan Al-Kuhlani5

  • 7/28/2019 Lecture6 Eng.alhassan

    6/27

    Relational Operators

    Examples:-

    Eng. Al-Hasan Al-Kuhlani6

  • 7/28/2019 Lecture6 Eng.alhassan

    7/27

    Logical operators.

    Logical operators provide a way to combine or negaterelational 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

    Eng. Al-Hasan Al-Kuhlani7

  • 7/28/2019 Lecture6 Eng.alhassan

    8/27

    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-Kuhlani8

  • 7/28/2019 Lecture6 Eng.alhassan

    9/27

    Logical operators

    Examples:-

    Eng. Al-Hasan Al-Kuhlani9

    R l i l d L i l

  • 7/28/2019 Lecture6 Eng.alhassan

    10/27

    Relational and LogicalFunctions

    Eng. Al-Hasan Al-Kuhlani10

  • 7/28/2019 Lecture6 Eng.alhassan

    11/27

    Flow Control

    Selection statements that test the results of relational or

    logical functions or operators are the decision-makingstructures that allow the flow of command execution to becontrolled.

    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)end Eng. Al-Hasan Al-Kuhlani11

  • 7/28/2019 Lecture6 Eng.alhassan

    12/27

    If-else-end Constructions

    Eng. Al-Hasan Al-Kuhlani12

    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

  • 7/28/2019 Lecture6 Eng.alhassan

    13/27

    if...end Structures:-

    The if statement evaluates a logical expression and

    executes a group of statements when the expression istrue .

    The optional elseif and else keywords provide for theexecution of alternate groups of statements.

    An end keyword, which matches the if, terminates the lastgroup of statements.

    The groups of statements are delineated by the fourkeywords 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 linescontaining if, else, end

    the end statement is required

    Eng. Al-Hasan Al-Kuhlani13

  • 7/28/2019 Lecture6 Eng.alhassan

    14/27

    Example (if)

    Here we construct a conditional statement which

    evaluates the function:

    Solution:

    If x>=0 & x1 & x

  • 7/28/2019 Lecture6 Eng.alhassan

    15/27

    Switch Selection Structure

    The switch selection structure provides an alternative tousing the if, elseif ,and else commands.

    The switch statement executes groups of statementsbased on the value of a variable or expression.

    Only the first matching case is executed.

    The syntax is:

    Eng. Al-Hasan Al-Kuhlani15

    switch expressioncase test expression 1

    statementscase {test expression 2, test expression 3}

    statements

    otherwise

    statements

    end

  • 7/28/2019 Lecture6 Eng.alhassan

    16/27

    Switch Example 1

    SwitchExample.m :

    switch x

    case 1

    disp(x is 1)

    case {2,3,4}

    disp(x is 2, 3 or 4)

    case 5

    disp(x is 5)

    otherwise

    disp(x is not 1, 2, 3, 4 or 5)

    end

    Eng. Al-Hasan Al-Kuhlani16

    >>x= 5>>SwitchExamplex is 5

  • 7/28/2019 Lecture6 Eng.alhassan

    17/27

    Switch Example 2

    month = input(Enterfirst three letters of the month: ,s);

    month = month(1:3); % Just use the first three lettersiflower(month)==feb

    leap = input(Is it a leap year (y/n): ,s);

    end

    switch lower(month)

    case {sep,apr,jun,nov}days = 30;

    case feb

    switch lower(leap)

    case y

    days = 29;otherwise

    days = 28;

    end

    otherwise

    days = 31;end Eng. Al-Hasan Al-Kuhlani17

    The number of days in a particularmonth.30 days to September April, Juneand NovemberAll the rest have 31Except February alone

    which has 28 days clearAnd 29 on leap year

  • 7/28/2019 Lecture6 Eng.alhassan

    18/27

    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 areexecuted once for every column in the expression,beginning with the first column and stepping through tothe last column.

    At each step, known as an iteration, the appropriate

    column of the expression is assigned to the variable.Eng. Al-Hasan Al-Kuhlani18

  • 7/28/2019 Lecture6 Eng.alhassan

    19/27

    For Loop

    Rules for writing and using a for loop include:

    1. If the expression results in an empty matrix, the loop willnot be executed.

    2. If the result of the expression is a scalar, the loop will beexecuted once.

    3. If the result of the expression is a vector, then each timethrough the loop, the variable will contain the next valuein the vector.

    4. A for loop cannot be terminated by reassigning the loopvariable within the loop.

    5. Upon completion of a for loop, the variable contains thelast value used.

    6. The colon operator can be used to define the expressionusing the following format

    for index = initial:increment:limit Eng. Al-Hasan Al-Kuhlani19

  • 7/28/2019 Lecture6 Eng.alhassan

    20/27

    For Loop

    Usually, expression is a vector of the form i:s:j.

    A simple example of for loop isfor ii=1:5

    x=ii*ii

    end

    The following statements form the 5-by-5 symmetricmatrix A with (i; j) element i/j forji:

    n = 5; A = eye(n);

    for j=2:n

    for i=1:j-1A(i,j)=i/j;

    A(j,i)=i/j;

    end

    end Eng. Al-Hasan Al-Kuhlani20

  • 7/28/2019 Lecture6 Eng.alhassan

    21/27

    For Example 1

    Using a for loop create a 1x10 vector where each entry isthe sum of its index and the square root of the previouselement (the zero element value is 0)

    Eng. Al-Hasan Al-Kuhlani21

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

    for i=1:10if (i == 1)

    x(i) = i;else

    x(i) = i + sqrt(x(i-1));end

    end

    x = zeros(1,10);

    prev_num = 0;for i=1:10

    x(i) = i + sqrt(prev_num);

    prev_num = x(i);end

  • 7/28/2019 Lecture6 Eng.alhassan

    22/27

    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

    Eng. Al-Hasan Al-Kuhlani22

  • 7/28/2019 Lecture6 Eng.alhassan

    23/27

    Conditional loops

    Suppose we now want to repeat a loop until a certaincondition is satisfied.

    This is achieved by making use of the MATLAB commandwhile , which has the syntax:

    while expression

    statements...

    end

    It is important to note that if the condition inside the

    looping is not well defined, the looping will continueindefinitely.

    If this happens, we can stop the execution by pressingCtrl-C.

    Eng. Al-Hasan Al-Kuhlani23

    x = 1

    while x

  • 7/28/2019 Lecture6 Eng.alhassan

    24/27

    While loop

    If all elements in expression are true, the commandsbetween the while and end statements are executed.

    The expression is reevaluated and if all elements are stilltrue, the statements are executed again.

    If the expression is false, control skips to the statementfollowing the end statement.

    The variables modified within the loop should include thevariables 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.

    Eng. Al-Hasan Al-Kuhlani24

  • 7/28/2019 Lecture6 Eng.alhassan

    25/27

    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).

    Eng. Al-Hasan Al-Kuhlani25

    z=1;while z

  • 7/28/2019 Lecture6 Eng.alhassan

    26/27

    Exercises

    Write a script to ask the user to input the scalarvalues for a, b, c, and x and then returns thevalue of ax+ bx+ c. The program repeats thisprocess until the user enters zero values for all

    four variables.

    Write a user-defined function to get the maximumvalue of three values.

    Write a user-defined function that searches amatrix input argument for the element with theminimum value and returns the indices of that

    element. Eng. Al-Hasan Al-Kuhlani26

  • 7/28/2019 Lecture6 Eng.alhassan

    27/27

    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.