CZ1102 Computing & Problem Solving Lecture 4

Embed Size (px)

Citation preview

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    1/26

    Arraysand

    Loops

    Week

    5

    ByJi Hui

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    2/26

    Array Whyweneedarray

    Batch

    inputting

    data

    for

    processing

    Vector Alsocalledlist,arraysinotherlanguage

    Rowvector

    Columnvector

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    3/26

    (Cont)

    Matrix

    Multidimensional

    array

    Vectorsarespecialcasesofmatriceswithone

    singlecolumnoronesinglerow

    Matrixand

    column

    vector

    will

    be

    discussed

    in

    futurelecturesonnumericallinearalgebra

    1,2,3,4

    5, 6, 7,8

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    4/26

    Vectorinitialization

    Initializeavector

    >>x=[130

    15]

    x=

    1 3 0 1 5

    >>whos

    Name Size Bytes Class Attributes

    x

    1x5

    40

    double

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    5/26

    Moreways

    of

    initialization

    Morewaystoinitializevector

    Canuse

    comma

    to

    separate

    items

    as

    you

    like

    >>x=[1,3,0,1,3]

    Dontforgetthecommas(orspaces)betweenelements,otherwise somethingunexpectedwill

    happen>>x=[130,13]

    Canuseonevectorinalistforanotherone

    >>a=[130];

    >>b=[1,3];

    >>c=[a,b]

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    6/26

    Initializingvectorsusingthecolon

    operator

    Avectorcanalsobegenerated(initialized)

    withthe

    colonoperator

    Integer

    j:kavector

    with

    elements

    j,

    j+1,j+2,...,k

    J:m:k

    whenm>0,avectorwithelementsj,j+m,j+2m,...,

    suchthat

    the

    last

    item

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    7/26

    Example Someexamples

    >>

    x=1:3:6x=

    1 4

    >>x=0.1:0.3:1.0

    x=

    0.1000 0.2000 0.5000 0.8000

    Whathappenwhenk>x=1:3:1

    x=

    Emptymatrix:1by0

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    8/26

    Transposing

    vectors

    Sofarallvectorsarerowvectors,howtoget

    columnvectors

    Usingdash

    >>x=[1,2,3]

    x=

    1

    23

    orusingsemicolon;

    >>x=[1;2;3]

    x=

    1

    23

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    9/26

    Howto

    access

    items

    in

    vector

    Subscript

    x(k):

    kth element

    of

    vector

    x

    >>x=[1,3,1,0,2];

    >>x(4)

    ans =

    0

    Asubscriptisindicatedinsideroundbrackets(alsocalledparentheses).

    Asubscript

    may

    be

    ascalar

    or

    avector.

    InMATLABsubscriptsalwaysstartat1.

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    10/26

    (cont)

    x(j:k):thevectorofjth,(j+1)th,,kth elements

    ofvector

    x

    >>x(2:4)

    ans =

    3 1 0

    Whataboutr(1:2:5)?

    Whatabout

    r([1

    25])?

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    11/26

    Repetition Whyweneedrepetition?

    Batchprocessingtheinputteddata

    Example

    (a)findthesquareofi=1,2,3,4,5,10? Withoutrepetition

    >>

    sqrt(1)>>sqrt(2)

    >>sqrt(3)

    .

    .>>sqrt(10)

    Toomanyrepetitivestatementsneeded

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    12/26

    (cont)

    (b)findthefactorialof5!

    Withoutrepetition

    >>1*2*3*4*5

    Whattodowith1000!?

    A struct fordoingsuchrepetitiveworksis

    needed

    Answer:for

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    13/26

    for struct Theforstruct

    for index=j:kstatements

    End

    or

    for index=j:m:kstatementsend

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    14/26

    Importantpoints

    for

    struct

    indexmustbeavariable.Eachtimethroughtheloopitwillcontain

    the

    next

    element

    of

    the

    vector

    j:kor

    j:m:k,

    and

    for

    each

    ofthesevalues,statements(whichmaybeoneormorestatement)arecarriedout.

    Oncompletionofthelooptheindexcontainsthelastvalue

    used. Ifthevectorj:korj:m:kisempty,statementsarenotexecuted,

    andcontrolpassestothestatementfollowingtheend

    statement.

    Theindex

    does

    not

    have

    to

    appear

    explicitly

    in

    statements.

    It

    is

    basicallyacounter.

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    15/26

    Example>>fori=1:5

    x(i)=sqrt(i);end

    >>x

    x=

    1.0000 1.4142 1.7321 2.0000 2.2361

    >>i

    i =

    5

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    16/26

    Samplecodes

    Calculating10!

    >>

    x

    =

    1;>>for i=2:10,

    x=x*i;

    end

    Calculating

    >>x=0;

    >>for k=1:50,

    x=x+k^2;end

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    17/26

    Acommon

    mistake:

    for

    less

    loops!

    Averycommonmistakeistoomitthewordfor

    fromafor

    loop.

    Insteadofreportinganerror,MATLABobliginglycreatesavector,andexecutesthestatementsin

    theloop

    only

    once.

    >>x=0

    >>i=1:6,

    x=x+i;end

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    18/26

    Moreon

    repetition

    foronlyworkswhenyouknowwhentostoptheloops Deterministic

    Whattodowhenyoudontknowwhentostop.

    Forexample,

    Problem:givenapositivefractionalnumberx,findthesmallestintegernthat>=x.i.e.ceil(x)providedinmatlab.

    Onesolution:

    count

    1,2,3,,

    stop

    until

    the

    integer

    >=x.

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    19/26

    Indeterministic

    repetition

    with

    while

    whilestructwhile

    condition

    statements

    end

    The

    while

    construct

    repeats

    statementsWHILEitsconditionremainstrue

    TheconditionistestedeachtimeBEFOREstatementsarerepeated.

    conditionmustdependonstatementsinsomeway,otherwisetheloopwillneverend.

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    20/26

    Programmingceil(x)

    for

    x>=0

    Samplecode

    >>x=5.4;

    >>n=0;

    >>while(n>n

    n=

    6

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    21/26

    Whattodowhenyouwanttofinish

    loopsearlier

    before

    its

    end

    breakstructwhile

    condition fori=j:k,

    statementsA statementsA

    if(condionB),break;end; if(conditionB),break;end;

    statementsB statementsBend end

    Duringeachrepetition,afterstatemensA is

    executed,if

    conditionB holds

    true,

    the

    while

    loopswillendimmediatelyandgotothenextlineaftertheloop.

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    22/26

    Example

    Sampleproblem:givenapositiveintegerN>2

    checkwhether

    it

    is

    prime

    or

    not?

    Solution:fori=3,N,checkwhetherthe

    divison N/iisintegerornot?

    Theinefficiency

    Noneedtocheckeveryinteger,aslongasthere

    existone

    integer

    such

    that

    the

    division

    is

    integer,

    itisnotaprime

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    23/26

    Codeusing

    forstruct

    >>x=935

    >>isprime=0;

    >>fori=3:xr=x/i;

    if(round(r)==r),

    isprime=0;

    endend

    >> isprime

    Isprime =

    0>>i

    i =

    935

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    24/26

    Bettercode

    using

    break

    >>x=935

    >>isprime=1;

    >>fori=3:x

    r=x/i;

    if(round(r)==r),

    isprime=0;

    break;end

    end

    >> isprime

    Isprime =0

    >>i

    i =

    5

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    25/26

    Whattodowhenyouwantexecute

    partof

    statements

    during

    the

    loops

    continuestructwhile

    condition fori=j:k,

    statementsA statementsA

    if(condionB),continue;end; if(conditionB)continue;end

    statementsB statementsB

    end end

    Ateachrepetition,afterstatementsA isexecuted,ifconditionB holdstrue,statementsB willnotbe

    executedand

    the

    program

    will

    start

    the

    next

    repetition.

  • 8/8/2019 CZ1102 Computing & Problem Solving Lecture 4

    26/26

    Thedifferencebetweenbreak and

    continue

    OnceconditionB holdes true

    break willfinish

    the

    whole

    loop

    and

    execute

    the

    lineafterend

    Continue willfinishonlythecurrentrepetitionof

    theloop

    and

    execute

    the

    next

    repetition

    of

    the

    loop.