[PDF] [PDF] Introduction to Matlab

create and manipulate string variables, e g compare two strings, concatenate Matlab is case sensitive, for example, a is written as a in Matlab; A will result in 



Previous PDF Next PDF





[PDF] chapter12_4_1, chapter12_4_2, and chapter12_4_3 - Elsevier

Solution via Series, Parallel, Feedback Commands: MATLAB can be used for block argument For example, G3 is 3, based on the fact that it is the third method using append and connect requires that all subsystems be proper (the order



[PDF] MATLAB Programming

For example, to create a one row matrix of five elements, type A = [12 62 93 -8 22 ]; manner, and concatenate this additional storage onto the original array



[PDF] Matlab - Université du Maine

Il y a plusieurs mani eres pour construire une matrice avec Matlab La premi ere, et peut Append the graph to le, rather than overwriting -Pprinter Specify the 



[PDF] Getting Started With MATLAB

of examples, so you should run MATLAB and follow along –v4 Create a file for MATLAB version 4 –append Append data to an existing MAT-file



[PDF] textscan

write to, and append to files when load and save cannot be used — MATLAB has functions to read from and write to many different file types, for example, 



[PDF] Matlab Reference

For more complicated feedback structures, use append and connect You can speciff static gains as regular matrices, for example, sys = feedback(sysl,2)



[PDF] MATLAB Data Import and Export - Computing Tutor

The -append option requests that the save function replace only the specified variable, B, and leave other variables in the file intact: load('example mat','B');



[PDF] Introduction to Matlab

create and manipulate string variables, e g compare two strings, concatenate Matlab is case sensitive, for example, a is written as a in Matlab; A will result in 

[PDF] append matlab list

[PDF] append matlab save

[PDF] append matlab string

[PDF] append matlab table

[PDF] append matlab vector

[PDF] apple accessories

[PDF] apple provisioning utility apu

[PDF] apple provisioning utility download

[PDF] apple support

[PDF] applescript indesign tutorial

[PDF] applet program for event handling in java

[PDF] application approach business

[PDF] application approach database

[PDF] application approach meaning in hindi

[PDF] application approach means

IntroductiontoMatlab

El˙zbietaP

ekalska

DelftUniversi tyofTechnology

2001-2005

Sendcommen tstopekalska@cs.man.ac.uk

Thismanual wasfirstprepare din2001to teachthestudentsofph ysicsbothprogramming(atleastsom econceptsofit) and

Contents

Introduction1

Preliminaries.................. .. ... ... ... ... ... ... ... .. ... 3

1GettingstartedwithMatlab4

1.1Inpu tviathecommand-li ne...... ......... .......................4

1.2help-facilities...... ... ... ... ... .. ... ... ... ... ... ... ... .. ... 5

1.3Inte rruptingacommandorprogram.............. ... ............... .6

1.4Path. ......... ... ... ... ... .. ... ... ... ... ... ... ... .. ... .6

1.5Worksp aceissues.......... ................. ... ... ... ... .. ... 6

1.6Savi ngandloadingdata..... ...... .............. ......... ... ... 7

2Basicsyntaxandvariables8

2.1Matlabasac alcu lator................. ... ... ... ... ... ... ... .. 8

2.2Ani ntroduc tiontofloating-pointnumbers......... ...... ...............8

2.3Assi gnmentsandvariables............... ...... ................. .9

3Mathematicswithvectorsandmatrices10

3.1Vect ors.............. .. ... ... ... ... ... ... ... ... .. ... ... .11

3.1.1Colonno tationandext ractingpartsofavector........ ...... .........11

3.1.2Columnv ectorsandtransposing. .............. ...... ..........12

3.1.3Product, divisionsandpowersofv ectors.................... ...... .13

3.2Matric es................ .. ... ... ... ... ... ... ... .. ... ... ..16

3.2.1Speci almatrices........... ................. ... ... ... ... 16

3.2.2Buildi ngmatricesandextractingpartsofmatri ces........... ...... ....17

3.2.3Operation sonmatrices............ ... .................. ... 20

4Visualization22

4.1Simp leplots............ ........... ... ... ... ... ... ... .. ... .22

4.2Sev eralfunctionsinonefi gure..................... ...... ...... ....23

4.3Other 2Dplottingfeatu res- optional.................................25

4.4Printi ng............... ... ... ... ... .. ... ... ... ... ... ... ..25

4.53Dlin epl ots.......... ........... ... ... ... ... ... ... .. ... ..26

4.6Plott ingsurfaces......... ................. ... ... ... ... ... ... 26

4.7Anim ations-optional.........................................27

5Controlflow28

5.1Logicala ndrelationalop erators...... .................. ......... .. .28

5.1.1Thecomma ndfind......................................30

5.2Condi tionalcodeexecution........ ........... ...................31

5.3Loops ............ ... .. ... ... ... ... ... ... ... ... .. ... ... .33

5.4Eva luationoflogicalandrelationalexpressionsin thecont rolflowstructur es........ ..35

6Numericalanalysis36

6.1Curv efitting..... .................. .. ... ... ... ... ... ... ... 37

6.2Inte rpolation..................... ... ... ... ... ... ... .. ... ..37

6.3Evalu ationofafunction...... ... ... .................... ... ... ..38

6.3.1Inline functions......... ........................ ... ... .. 38

6.4Inte grationanddi

erentiation............... ... ... ... ... ... .. ... ..39

6.5Num ericalcomputationsandthecont rolflowstructures.............. ...... ..40

7Scriptandfunctionm-files40

7.1Scrip tm-files....... .................. ... .. ... ... ... ... ... .41

7.2Func tionm-file............ ............... ... ... ... ... .. ... .42

7.2.1Speci alfunctionvariables.... .................... ...........44

7.2.2Localand globalvariables... ..... ......... .................. 45

7.2.3Indirectf unctionevaluation-optional............................45

7.3Scrip tsvs.functions..... ........ ........................ .. ... 46

8Text48

8.1Charact erstrings........... .............. ... ... ... ... .. ... ..48

8.2Text inputandoutpu t.............. ...... .............. ... ... .50

9Cellarraysandstructures-optional52

9.1Cell arrays......... ......... .. ... ... ... ... ... ... ... .. ... ..52

9.2Struc tures................... ... ... ... .. ... ... ... ... ... ... 53

10Optim izingtheperformanceofMatlabcode55

10.1Vect orization-speed-upofcomputations.. ... ....................... ..55

10.2Arrayp reallocation. .......................... ... ... ... ... .. ..56

10.3Matlab'stricksandtips.... ......... ........ ... ... ... ... ... ... 57

11Fil einput/outputoperations60

11.1Text files........ ........... ... ... ... ... ... ... ... .. ... ... 61

11.2Bin aryfiles-optional.........................................62

12Wr itinganddebuggingMatlabprograms63

12.1Stru cturalprogramming........... ................. ... ... ... ... 63

12.2Debu gging................. ... ... ... ... ... ... ... ... .. ... ..65

12.3Recom mendedprogrammingstyle............ ................. ......66

Introduction

Duringthiscourse you willlearnhowto useMatlab,todesign,andtoperformmathematicalcomputations. Youwill alsogetacqua intedwithba sicprogra mming.Ifyoulearntousethisprog ramwell,youw illfindit veryuseful infuture,sinceman ytechn icalormathematicalpr oblemscanbesolve dusingMatlab. Thistextin cludesallmat erial(withsomeadditional informati on)thatyouneedtoknow,how ever,many thingsaret reatedbriefly.T herefore,"TheStudentEditionof Matlab"user'sguide shouldbeusedasa complementarybookduringthecourse. Asignofabookaccompaniedbypagenumbers,placed onthe leftmar gin,indicateswhereyouc anfindmoreinfor mation.Readthes uggestedpagest obetterunderstand theconcepts discussed.Whereno reference tothebookappears,itmeansthatonlythistextexplainssome ideas,sincetheymig htbemoreabo utgeneralpro grammingthana boutMatlab.Exercisesaremarkedwith Thetext ofthisc ourseincludes someoptio nalpartsforvolunteersorfo rmor eadvancedstudents.Sucha part

isenclosedb etw eentwohorizontallines,withthe word'optional'onthe firstline. Thereis alsoan'intermezzo'

part,whichisnotessen tial,butprovidesso meimp ortant information.Ifyoualrea dyk nowhowtoprogra m inala ngu age,likePascalorC,thenyou mayfind iteasierormoreintere stingto dotheo ptionalpartsa s well.However, ifyoudonothaveanyidea about programmi ng,ple asefeelfr eetoskiptho sefragmen ts.Itis importantthatyouspendenoughtime tolearntheMatlabbasics.

Pleasetestafter eachsectionwhe theryouhaves u

cientunderstanding oftheissuesdiscussed.Usethelists providedbelow.

Sections1-2.

Youshou ldbeableto:

•recognizebuilt-invariab les; •defineva riablesandperformcomputat ionsusingthem; •performbasicmathem aticaloperations ; •knowhowt osuppressdispla ywith;(semicolon); •usethe formatcommandtoadjusttheCo mmandwindo w; •addandrem ovevariabl esfromtheworkspace;c heckwhichvariablesarecurrent lypresent inthe workspace; •useon- linehelptoge tmoreinfo rmationonaco mmandandknowhowtousethelookforcommand; •usethe loadandsavecommandstoread/savedatatoa file; •accessfiles atdi!erentdirectories( manipulatepath-changingcommands);

Section3.

Youshou ldbeableto:

•createvectors andmatriceswithdirect assignment(using []); •uselinspacetocreatev ectors; •createrandomv ectorsandmatrices; •creatematrices viathe commands:eyeones ,zerosanddiag; •buildalarge rma trixfromsmallerone s; •usecol onnotationtocrea tevectorsandextractra ngesofe lementsfromvector sandmatrices; •extractelement sfromvectorsandmatriceswithsubscript notation,e.g. x(5),A(i,j); •applytransposeoperat orstovectorsandmatrices; •performlegaladditio n,subtraction, andmultiplicationoperations onvectorsandmatrices; •understandtheuseofdoto per ator s,like.*,./,...a ndknowwhythey aredi!erentfromthe regular*, /,...o perators; •deleteelements fromvectorsa ndmatrices; •computeinnerpro ductsan dtheEuclideanlengtho fvectors; •createandm anipulat ecomplexvectors andmatrices.

Section4.

Youshou ldbeableto:

•uset heplotcommandtomakesi mpleplot s; •knowhowto useholdon/off 1 •plotsevera lfunctionsinonefigureeitherino negraphicalwindowor byc reatinga fewsmallerones(the useof subplot); •addatit le,gri dandalegend,describet heaxes,c hangethe range ofaxes; •uselog arithmicaxes; •makesimple3Dlineplo ts; •plotsurface s,contours,changecolors; •sendfig urestotheprinter orpr intt hemtoafile; •optional:makesomefancyp lots; •optional:createMatlabanimations.

Section5.

Youshou ldbeableto:

•user elationaloperators:<,<=,>, >=,==,~=andlogicalo perators:&,|and~; •understandthelogicaladdr essing; •fullyunder standhowtousethecomma ndfind,bothonvectorsandmatrices; •usefor-loopsandwhile-loopsandknow thedi!erencebe tweenthem; •understandhowlogicalexpr essionsar eevaluatedinthecont rolflowstructures.

Section6.

Youshou ldbeableto:

•createandm anipulat eMatlabpolynomials; •fitap oly nomialtodata; •interpolatethedata; •evaluateafunction; •createinlinefunctions; •integrateanddi!erentiateafunction; •optional:understandhowtomake approximat ionsofT aylorexpansionswiththegivenpr ecision.

Section7.

Youshou ldbeableto:

•edita ndrunanm- file(bothfunctio nsandscripts); •identifythedi!erencesbe tweenscriptsandfunctions; •understandtheconceptoflo cal andglobalvaria bles; •createafunctionwitho neo rmoreinputarg ument sandoneor moreoutput arguments; •useco mmentstatementstodocumentscripts andfunctions; •optional:usethe fevalcommand-knowhow topass afunctionnameasa ninputarg umentto another function.

Sections8-9.

Youshou ldbeableto:

•createandmanipulat estringva riables,e.g.comparetw ostrings,conca tenatethem,findasubstringin •usefr eelyandwithunderstandingthe textinput/outputco mmands:input,dispandfprintf; •optional:operateoncellarra ysandstr uctures;

Section10.

Youshou ldbeableto:

•preallocatememoryfo rvector sormatricesandknowwhyandwhenthisisbeneficial; •replacebasicloop swithvectorized operations; •usecolo nnotationtoperfo rmvectorizedoperatio ns; •understandthetwowayso faddr essingmatrixelementsusinga vectorasanindex:tr aditionala ndlogical indexing; •usearra yindexinginsteadofloo pstoselectelementsf rom amatrix; 2 •uselogi calindexingandlogicalfunct ionsinsteadofloops tosele ctelementsfrommatric es; •understandMatlab'stricks.

Section11.

Yousho uldbeableto:

•performlowlevelinp utandoutp utwithfopen,fscanfandfclose; •understandhowtooper ateontextfiles (input/outputoper ations); •getmoreun derstand ingontheuseoffprintfwhilewriting toafile; •optional:understandhowtooper ateonbinar yfiles(input/output operations);

Section12.

Youshou ldbeableto:

•knowandunder standtheimp ortanceofstructuralpr ogr amminganddebugging; •knowhowto debugyour program ; •haveanideahowt owritepro gra msusingthe recommendedpro grammingstyle.

Preliminaries

Belowyoufind afewbasicdefinitions onc omputer sandpro gramming.P leasegetacquaintedwith themsince theyintro ducekeyconceptsneededinthe comings ections: onlyoneoftw ovalues: 0or1.More meaningful informationisobtai ned byc omb iningconsecut ivebits intolarger units,suchasbyte. indicatedintermsofkilobyt es( 1024bytes),meg abytes (1024kilobytes),andgigab ytes(1024megab ytes). •Binarysyste m-anumbersystemthathastwouniquedigits:0and1.Computersarebasedonsuch asystem,becauseofitselectricalnature(chargedversusu ncharged).Eachdigi tpositionr epresentsa di erentpowerof2 .Thepowersof2incr easewhile movingfromthe rightmost totheleftmostposition, startingfrom2 0 =1.Her eisanexampleofabinarynumberanditsrepresentationinthedecimal system:

10110=1 !2

4 +0!2 3 +1!2 2 +1!2 1 +0!2 0 =16+0+4+2+0=24.Becausecomputers usethe binarynum bersystem,powers of2playanimportantr ole, e.g.8(=2 3 ),64 (=2 6 ),12 8(=2 7 or256( =2 8 •Dataisinfor mationrepresentedwithsymbols,e.g.numb ers,words,signalsorimages. •Acommandisainstr uctionto doaspecifictask. •Analgorithmisas equenceof instructionsfo rthesolution ofaspecifictaskinafiniten umberofsteps. •Aprogramistheimplemen tat ionofanalgorithmsuitablefore xecutionbyac omputer. •Avariableisacon tainerthatcan holdavalue. For example,i ntheexpression:x+y,xandyarevari ables. Theycanr epresentn umericvalues,like25.5,characters,like'c'orch aracterstrings,like'Matlab'. Variablesmakeprogramsmor eflexible.Whe naprogramisexecuted,the variablesar ethenreplaced withrealda ta.Thatiswhyth esameprogramca nprocessd i erentsetsofdat a. Everyvariab lehasaname(calledthevariablena me)andadatatype.Avariable'sdatatypeindicates thesort ofvaluethatth evaria blerepresents(se ebelow). •Aconstantisav aluetha tneverchanges.T hatmak esittheoppositeo favariable.Itca nbeanumeric value,acharacter ora string. •Adatatypeisac lassificat ionofaparticulartypeofinfo rmation. Themo stbasicdatatypesa re: !16 •character:readabletextcharacter,e.g. 'p'. •Abugisan errorin aprogram,causingthe progra mtosto prunning,nottorunatallortoprovide wrongresults.Somebugs canbev erysubtleandhard tofind.Thepr ocessoffindingandr emovingbugs iscalled debugging. •Afileisac ollec tionofdataorinformation thatha saname,store dinacom puter.Therearemany di erenttypesoffi les:datafiles,programfiles,text filesetc. •AnASCIIfileisas tandar dized,readableandeditableplaintextfile. •Abinaryfileisafi lestor edinafo rmat,whichiscom puter-r eadable butnothuman-readable.Most numericdataandallex ecutablepro gramsares toredinbi naryfiles.Matlabbinaryfilesaretho sewith theex tension'*.mat'. 3

1GettingstartedwithMatlab

Matlabisat ool formathematic al(techn ical)calculations.First,itcanbeusedasas cientificcalculator.

Next,ita llowsy outoplotor visualizedatain manydi

erentways,pe rformmatrixa lgebra,workwith polynomialsorintegratefunction s.Like inaprogrammablecalculator, youcancreate,executeandsavea sequenceofcommand sin ordertomakeyourcomputat ionalp rocessautomatic .Itcanb eusedtostore or retrievedata.Intheend, Matlabcanal sobetreatedasauser-fr iendly programmingla ngu age,wh ichgives thepo ssibilitytohandlemathematica lcalculation sinaneasy way.Insummary,asacomputing/p rogramming environment,Matlabisespecially designedtoworkwith datasetsas awhol esu chasvectors,matri cesand images.Theref ore,PRTOOLS(http://prtools.org),atoolboxforPatternRecognition,andDIPIMAGE (http://www.ph.tn.tudelft.nl/DIPlib/dipimage1.html),atoolboxforImage Processin g,havebeendeveloped underMatlab. UnderWindo ws,youcanstar tMatlabbydo ubleclickingontheMatlabiconthatsh ouldbeonthede sktop ofyou rcomputer. Onaunixsystem,typematlabatth ecommandlin e.RunningMatlabcreatesone or morewindowsony ourscreen.The mostimport antistheCommandWindow,whichistheplaceyouinteract (orEDU>>fortheStudent Edition).Whent heCommandWindow isactive,acur sorappear safterthe prompt, indicatingthatMatlabiswa itingforyourcomma nd.Matlabrespondsbyprintingtex tinthe Command Windoworby creat ingaFigureWindowforgraphics. ToexitMatlabusethe commandexitorquit. Control-Cisa loca labortwhichkillsthec urrentexecutionofacommand.

1.1Input viathecommand-line

2-10 Matlabisan interactives ystem;commandsfollowedbyEnterareexecuted immediately.Theresults are, ifdesire d,displayedonscr een.However,executiono facommand willbepossibleifthec ommandistyped accordingtotherules.Tab le1sho wsalistof commandsusedtosolv eindicatedmat hem aticalequations(a, b,xandyarenu mbers).Belowyoufindbasicinf ormationtohelpyoust artingwi thMatlab: •CommandsinMatlabareexecutedb ypressing EnterorReturn.Theoutputwillbedisplayedon screenimmediately. Trythefollowing(hitEnteraftertheend ofline): >>3+ 7.5 >>18/4 >>3* 7

Notethats pacesare notimportantinMatlab.

•Theresult ofthelast perfor medcomputat ionisascr ibedtothevariableans,whichisanexampleofa Matlabbuilt-invaria ble.Itcanbeusedinthesubsequentco mmand.F orinstance: >>14/4 ans=quotesdbs_dbs14.pdfusesText_20