cz1102 computing & problem solving lecture 10

Upload: charmaine-chu

Post on 09-Apr-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

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

    1/24

    EfficientProgramming

    in

    Matlab

    Week12

    ByJI,Hui

    BasedonWritingFastMATLABCodeby PascalGetreuer

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

    2/24

    Introduction

    Matlab isainterpretedlanguage,meaningit

    focuseson

    the

    ease

    of

    development

    with

    languageflexibility,interactivedebugging,and

    otherconveniences

    Itlackstheperformanceofthosecompiled

    languageslikeCandC++.WhileMatlab may

    notbe

    as

    fast

    as

    C,

    there

    are

    ways

    to

    bring

    it

    closer.

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

    3/24

    Organizationof

    your

    project

    Useaseparatefolderforeachproject.

    Writecomments,

    especially

    write

    the

    help

    commentforfunctions

    Savefrequent

    console

    commands

    as

    ascript

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

    4/24

    Commendsforhelpingmeasuring

    efficiency

    usethetic/toc stopwatchtimer

    tic Startastopwatch

    timer

    toc Readthestopwatchtimer

    Donotuseinputtic/toc indifferentprompts,itwill

    count

    the

    typing

    time Usingitinasinglelineoruseitinscript

    >>tic;sin(rand(1,10^6));toc

    Elapsedtime

    is

    0.055057

    seconds.

    >>tic;

    >>toc

    Elapsedtime

    is

    0.743795

    seconds.

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

    5/24

    Oneway

    for

    array

    allocation

    Dynamicallocation,thatis,dynamically

    augmentrows

    and

    columns

    of

    arrays

    e.g.

    >>a=2

    a=

    2

    >>a(2,6)=1

    a=

    2 0 0 0 0 0

    0 0 0 0 0 1

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

    6/24

    (cont)

    Matlab willautomaticallyresizethematrix

    Internally,the

    matrix

    data

    memory

    must

    be

    reallocated

    withlargersize.

    Theoverhead(cost)canbesignificantifthematrixis

    resized

    repeatedly,

    e.g.

    like

    within

    a

    loop Ittakes1.2secondsinacomputerwithcorei5CPU

    clearab

    tic

    a(1)=1;

    b(1)

    =0;

    fork=2:30000

    a(k)=0.99803*a(k1) 0.06279*b(k1);

    b(k)=0.06279*a(k1)+0.99803*b(k1);

    end;

    toc

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

    7/24

    Anotherway

    for

    array

    allocation

    Preallocate thematrixwiththezeros

    commandsto

    avoid

    frequent

    reallocations

    e.g. Ittakesonly0.009514secondstorunthe

    followingcode,150timesfasterthandynamic

    allocation

    tic;a =zeros(1,30000);%Preallocation

    b=zeros(1,30000);

    a(1)

    =

    1;b(1)

    =

    0;fork=2:30000

    a(k)=0.99803*a(k1)0.06279*b(k1);

    b(k)=0.06279*a(k1)+0.99803*b(k1);

    end;toc

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

    8/24

    Whatif

    the

    final

    array

    size

    can

    vary?

    Makingthetradeoffbetweenstorage

    efficiencyand

    computing

    efficiency.

    Preallocatealargerarrayandtrimextrazeros.

    e.g.3.8525secs vs 0.0213secs

    a=zeros(1,50000);%Preallocate

    count=0;

    fork=1:50000

    v=exp(rand*rand);

    ifv>0.5

    %

    Conditionally

    add

    to

    array

    count=count+1;

    a(count)=v;

    end;end

    a=a(1:count);

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

    9/24

    Vecterization

    Acomputationisvectorized bytaking

    advantageof

    vector

    operations.

    Avarietyofprogrammingsituationscanbe

    vectorized,andoftenimprovingspeedto10

    timesfasterorevenbetter.

    Vectorization isoneofthemostgeneraland

    effectivetechniques

    for

    writing

    fast

    Matlab

    codes.

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

    10/24

    Vectorized Computations

    Manystandardmathematicalfunctionsare

    vectorizedin

    Matlab

    theycanoperateonanarrayasifthefunctionhad

    beenappliedindividuallytoeveryelement.

    >>sqrt([1,4;9,16])

    ans=

    1

    2

    3 4

    >>abs([0,1,2,5,6,7])

    ans=

    0

    1

    2

    5

    6

    7

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

    11/24

    Oneexampleofvecterized

    computation

    Problem:Findthemindistancebetweenaset

    ofpoints

    and

    the

    origin

    Nonvecterized code

    functiond=minDistance1(x,y,z)

    %Find

    the

    min

    distance

    between

    aset

    of

    points

    and

    the

    origin

    nPoints =length(x);

    d=zeros(nPoints,1); %Preallocate

    fork=1:nPoints %Computedistanceforeverypoint

    d(k)=sqrt(x(k)2

    +y(k)2

    +z(k)2);

    end

    d=min(d); %Gettheminimumdistance

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

    12/24

    (cont)

    Vecterized code

    Thecomparison:vecterized code30timesfaster

    >>featureaccel off; %ForMatlab 7

    >>x=rand(1,30000);y=rand(1,30000);z=rand(1,30000);

    >>tic;minDistance2(x,y,z);toc;

    Elapsedtimeis0.002272seconds.

    >>tic;minDistance1(x,y,z);toc

    Elapsedtimeis0.060647seconds.

    functiond=minDistance2(x,y,z)

    %Findthemindistancebetweenasetofpointsandtheorigin

    d=sqrt(x.2+y.2+z.2); %Computedistanceforeverypoint

    d=min(d); %Gettheminimumdistanc

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

    13/24

    Someusefulfunctionsupporting

    vecterization

    Min

    max sum,

    cumsum,

    prod,

    cumprod

    sort diff

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

    14/24

    Vectorized Logic

    Bottleneckcodeofteninvolvesconditional

    logic

    Likecomputations,Matlab's logicoperators

    arealsovectorized:

    Twoarraysarecomparedperelement.Logic

    operationsreturnlogicalarrayswithbinaryvalues.

    >>[1,5,3]

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

    15/24

    Threepowerfulcommandsforlogical

    arrays

    find:Findindicesofnonzeroelements

    any:Trueifanyelementofavectorisnonzero

    (orpercolumnforamatrix)

    >>find([1,5,3]

    >any([1,5,3]

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

    16/24

    (cont)

    all:Trueifallelementsofavectorarenonzero

    (orper

    column

    for

    amatrix)

    Vecterized logic alsoworksformatrices

    >>all([1,5,3]>find(eye(3)==1)

    ans =

    1

    5

    9

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

    17/24

    Example1

    Problem: removenegativeelementsfromthe

    array V1:Nonvecterized code

    y=x; %Preallocate

    count=0;

    fork=1:length(x),

    if(x(k)>=0)

    count=count+1;

    y(count)=x(k);end;

    end;

    y=y(1:count);

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

    18/24

    (cont)

    V2:Vecterized code

    V3:

    Further

    streamlined

    version

    Timecomparison inseconds

    V1:V2:V3 =0.04:0.0031:0.0010

    idx=find(x>0);%Findelementsthatarenonpositive

    y =x(idx);

    y=x(find(x>0));

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

    19/24

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

    20/24

    Referencingoperations

    ReferencinginMatlab isvariedandpowerful

    enough.

    Goodunderstandingofreferencingenables

    vectorizing abroaderrangeofprogramming

    situations.

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

    21/24

    Subscriptsvs.

    Indices

    Subscriptsarethemostcommonmethod

    usedto

    refer

    to

    matrix

    elements,

    for

    example,

    A(3,9)referstorow3,column9.

    Indicesareanalternativereferencingmethod

    formatrix byviewingitasavector

    Anindex referstoanelement'spositioninthis

    one

    dimensional

    vector Fora10by10matrix,A(83)alsorefersA(3,9)

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

    22/24

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

    23/24

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

    24/24

    DeletingSub

    matrices

    with

    []

    Elementsinamatrixcanbedeletedby

    assigningthe

    empty

    matrix.

    A(2,:)=[]deletesthesecondrowofA

    A([3,5])=[]deletestheelementA(3,5)fromAand

    reshapeA

    to

    avector

    DeletionslikeA(2,1)=[]is illegal.