INTRODUCTION TO MATLAB FOR ENGINEERING STUDENTS 面向工程專(zhuān)業(yè)學(xué)生的 MATLAB 簡(jiǎn)介_(kāi)第1頁(yè)
INTRODUCTION TO MATLAB FOR ENGINEERING STUDENTS 面向工程專(zhuān)業(yè)學(xué)生的 MATLAB 簡(jiǎn)介_(kāi)第2頁(yè)
INTRODUCTION TO MATLAB FOR ENGINEERING STUDENTS 面向工程專(zhuān)業(yè)學(xué)生的 MATLAB 簡(jiǎn)介_(kāi)第3頁(yè)
INTRODUCTION TO MATLAB FOR ENGINEERING STUDENTS 面向工程專(zhuān)業(yè)學(xué)生的 MATLAB 簡(jiǎn)介_(kāi)第4頁(yè)
INTRODUCTION TO MATLAB FOR ENGINEERING STUDENTS 面向工程專(zhuān)業(yè)學(xué)生的 MATLAB 簡(jiǎn)介_(kāi)第5頁(yè)
已閱讀5頁(yè),還剩69頁(yè)未讀 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶(hù)提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

INTRODUCTIONTOMATLABFORENGINEERINGSTUDENTS

DavidHoucqueNorthwesternUniversity

(version1.2,August2005)

PAGE\*roman

viii

Contents

1

Tutoriallessons1

1

1.1 Introduction....................................

1

1.2 Basicfeatures...................................

2

1.3 AminimumMATLABsession..........................

2

1.3.1 StartingMATLAB............................

2

1.3.2 UsingMATLABasacalculator.....................

4

1.3.3 QuittingMATLAB............................

5

1.4 Gettingstarted..................................

5

1.4.1 CreatingMATLABvariables.......................

5

1.4.2 Overwritingvariable...........................

6

1.4.3 Errormessages ..............................

6

1.4.4 Makingcorrections............................

6

1.4.5 Controllingthehierarchyofoperationsorprecedence.........

6

1.4.6 Controllingtheappearanceoffloatingpointnumber..........

8

1.4.7 Managingtheworkspace.........................

8

1.4.8 Keepingtrackofyourworksession...................

9

1.4.9 Enteringmultiplestatementsperline..................

9

1.4.10Miscellaneouscommands.........................

10

1.4.11Gettinghelp................................

10

1.5 Exercises......................................

11

Tutoriallessons2 12

Mathematicalfunctions 12

Examples 13

Basicplotting 14

overview 14

Creatingsimpleplots 14

Addingtitles,axislabels,andannotations 15

Multipledatasetsinoneplot 16

Specifyinglinestylesandcolors 17

Exercises 18

Introduction 19

Matrixgeneration 19

Enteringavector 19

Enteringamatrix 20

Matrixindexing 21

Colonoperator 22

Linearspacing 22

Colonoperatorinamatrix 22

Creatingasub-matrix 23

Deletingroworcolumn 25

Dimension 25

Continuation 26

Transposingamatrix 26

Concatenatingmatrices 26

Matrixgenerators 27

Specialmatrices 28

Exercises 29

ArrayoperationsandLinearequations 30

Arrayoperations 30

Matrixarithmeticoperations 30

Arrayarithmeticoperations 30

Solvinglinearequations 32

Matrixinverse 33

Matrixfunctions 34

Exercises 34

IntroductiontoprogramminginMATLAB 35

Introduction 35

M-FileScripts 35

Examples 36

Scriptside-effects 37

M-Filefunctions 38

AnatomyofaM-Filefunction 38

Inputandoutputarguments 40

Inputtoascriptfile 40

Outputcommands 41

Exercises 42

Controlflowandoperators 43

Introduction 43

Controlflow 43

The‘‘if...end’’structure 43

Relationalandlogicaloperators 45

The‘‘for...end’’loop 45

The‘‘while...end’’loop 46

Otherflowstructures 46

Operatorprecedence 47

Savingoutputtoafile 47

Exercises 48

DebuggingM-files 49

Introduction 49

Debuggingprocess 49

Preparingfordebugging 50

Settingbreakpoints 50

Runningwithbreakpoints 50

Examiningvalues 51

Correctingandendingdebugging 51

Endingdebugging 51

CorrectinganM-file 51

ASummaryofcommands 53

ReleasenotesforRelease14withServicePack2 58

Summaryofchanges 58

Otherchanges 60

Furtherdetails 60

MaincharacteristicsofMATLAB 62

History 62

Strengths 62

Weaknesses 63

Competition 63

ListofTables

Basicarithmeticoperators............................ 5

Hierarchyofarithmeticoperations........................ 7

Elementaryfunctions 12

Predefinedconstantvalues 13

Attributesforplot 18

Elementarymatrices 27

Specialmatrices 28

Arrayoperators 31

Summaryofmatrixandarrayoperations 32

Matrixfunctions 34

AnatomyofaM-Filefunction 38

Differencebetweenscriptsandfunctions 39

Exampleofinputandoutputarguments 40

dispandfprintfcommands 41

Relationalandlogicaloperators 45

Operatorprecedence 47

Arithmeticoperatorsandspecialcharacters 53

Arrayoperators 54

Relationalandlogicaloperators 54

Managingworkspaceandfilecommands 55

Predefinedvariablesandmathconstants 55

Elementarymatricesandarrays 56

ArraysandMatrices:Basicinformation 56

ArraysandMatrices:operationsandmanipulation 56

ArraysandMatrices:matrixanalysisandlinearequations 57

ListofFigures

ThegraphicalinterfacetotheMATLABworkspace.............. 3

Plotforthevectorsxandy 15

PlotoftheSinefunction 16

Typicalexampleofmultipleplots 17

Preface

“IntroductiontoMATLABforEngineeringStudents”isadocumentforanintroductorycourseinMATLABQR1andtechnicalcomputing.ItisusedforfreshmenclassesatNorth-

westernUniversity.Thisdocumentisnotacomprehensiveintroductionorareferenceman-ual.Instead,itfocusesonthespecificfeaturesofMATLABthatareusefulforengineeringclasses.Thelabsessionsareusedwithonemaingoal:toallowstudentstobecomefamiliarwithcomputersoftware(e.g.,MATLAB)tosolveapplicationproblems.WeassumethatthestudentshavenopriorexperiencewithMATLAB.

TheavailabilityoftechnicalcomputingenvironmentsuchasMATLABisnowreshapingtheroleandapplicationsofcomputerlaboratoryprojectstoinvolvestudentsinmoreintenseproblem-solvingexperience.Thisavailabilityalsoprovidesanopportunitytoeasilyconductnumericalexperimentsandtotacklerealisticandmorecomplicatedproblems.

Originally,themanualisdividedintocomputerlaboratorysessions(labs).Thelabdocumentisdesignedtobeusedbythestudentswhileworkingatthecomputer.Theemphasishereis“l(fā)earningbydoing”.Thisquiz-likesessionissupposedtobefullycompletedin50minutesinclass.

ThesevenlabsessionsincludenotonlythebasicconceptsofMATLAB,butalsoanin-troductiontoscientificcomputing,inwhichtheywillbeusefulfortheupcomingengineeringcourses.Inaddition,engineeringstudentswillseeMATLABintheirothercourses.

Theendofthisdocumentcontainstwousefulsections:aGlossarywhichcontainsthebriefsummaryofthecommandsandbuilt-infunctionsaswellasacollectionofreleasenotes.Thereleasenotes,whichincludeseveralnewfeaturesoftheRelease14withServicePack2,wellknownasR14SP2,canalsobefoundinAppendix.AlloftheMATLABcommandshavebeentestedtotakeadvantagewithnewfeaturesofthecurrentversionofMATLABavailablehereatNorthwestern(R14SP2).Although,mostoftheexamplesandexercisesstillworkwithpreviousreleasesaswell.

ThismanualreflectstheongoingeffortoftheMcCormickSchoolofEngineeringandAppliedScienceleadingbyDeanStephenCarrtoinstituteasignificanttechnicalcomputing

intheEngineeringFirstQR2coursestaughtatNorthwesternUniversity.

Finally,thestudents-EngineeringAnalysis(EA)Section-deservemyspecialgrati-tude.Theywereveryactiveparticipantsinclass.

DavidHoucqueEvanston,IllinoisAugust2005

1MATLABQRisaregisteredtrademarkofMathWorks,Inc.

2EngineeringFirstQRisaregisteredtrademarkofMcCormick

SchoolofEngineeringandAppliedScience(NorthwesternUniversity)

Acknowledgements

IwouldliketothankDeanStephenCarrforhisconstantsupport.Iamgratefultoanumberofpeoplewhoofferedhelpfuladviceandcomments.IwanttothanktheEA1instructors(FallQuarter2004),inparticularRandyFreeman,JorgeNocedal,andAllenTaflovefortheirhelpfulreviewsonsomespecificpartsofthedocument.IalsowanttothankMalcombMacIver,EA3Honorsinstructor(Spring2005)forhelpingmetobetterunderstandtheanimationofsystemdynamicsusingMATLAB.Iamparticularlyindebtedtothemanystudents(340orso)whohaveusedthesematerials,andhavecommunicatedtheircommentsandsuggestions.Finally,IwanttothankITpersonnelforhelpingsettinguptheclassesandothercomputerrelatedwork:RebeccaSwierz,JesseBecker,RickMazec,AlanWolff,KenKalan,MikeVilches,andDanielLee.

Abouttheauthor

DavidHoucquehasmorethan25years’experienceinthemodelingandsimulationofstruc-turesandsolidcontinuaincluding14yearsinindustry.Inindustry,hehasbeenworkingasR&Dengineerinthefieldsofnuclearengineering,oilrigplatformoffshoredesign,oilreser-voirengineering,andsteelindustry.Alloftheseincludeworkingindifferentinternationalenvironments:Germany,France,Norway,andUnitedArabEmirates.Amongotherthings,hehasacombinedbackgroundexperience:scientificcomputingandengineeringexpertise.HeearnedhisacademicdegreesfromEuropeandtheUnitedStates.

HereatNorthwesternUniversity,heisworkingunderthesupervisionofProfessorBrianMoran,aworld-renownedexpertinfracturemechanics,toinvestigatetheintegrityassess-mentoftheaginghighwaybridgesundersevereoperatingconditionsandcorrosion.

PAGE

10

Chapter1

Tutoriallessons1

Introduction

Thetutorialsareindependentoftherestofthedocument.Theprimarilyobjectiveistohelpyoulearnquicklythefirststeps.Theemphasishereis“l(fā)earningbydoing”.Therefore,thebestwaytolearnisbytryingityourself.WorkingthroughtheexampleswillgiveyouafeelforthewaythatMATLABoperates.InthisintroductionwewilldescribehowMATLABhandlessimplenumericalexpressionsandmathematicalformulas.

ThenameMATLABstandsforMATrixLABoratory.MATLABwaswrittenoriginallytoprovideeasyaccesstomatrixsoftwaredevelopedbytheLINPACK(linearsystempackage)andEISPACK(Eigensystempackage)projects.

MATLAB[1]isahigh-performancelanguagefortechnicalcomputing.Itintegratescomputation,visualization,andprogrammingenvironment.Furthermore,MATLABisamodernprogramminglanguageenvironment:ithassophisticateddatastructures,containsbuilt-ineditinganddebuggingtools,andsupportsobject-orientedprogramming.ThesefactorsmakeMATLABanexcellenttoolforteachingandresearch.

MATLABhasmanyadvantagescomparedtoconventionalcomputerlanguages(e.g.,C,FORTRAN)forsolvingtechnicalproblems.MATLABisaninteractivesystemwhosebasicdataelementisanarraythatdoesnotrequiredimensioning.Thesoftwarepackagehasbeencommerciallyavailablesince1984andisnowconsideredasastandardtoolatmostuniversitiesandindustriesworldwide.

Ithaspowerfulbuilt-inroutinesthatenableaverywidevarietyofcomputations.Italsohaseasytousegraphicscommandsthatmakethevisualizationofresultsimmediatelyavailable.Specificapplicationsarecollectedinpackagesreferredtoastoolbox.Therearetoolboxesforsignalprocessing,symboliccomputation,controltheory,simulation,optimiza-tion,andseveralotherfieldsofappliedscienceandengineering.

InadditiontotheMATLABdocumentationwhichismostlyavailableon-line,wewould

recommendthefollowingbooks:[2],[3],[4],[5],[6],[7],[8],and[9].Theyareexcellentintheirspecificapplications.

Basicfeatures

Aswementionedearlier,thefollowingtutoriallessonsaredesignedtogetyoustartedquicklyinMATLAB.ThelessonsareintendedtomakeyoufamiliarwiththebasicsofMATLAB.Weurgeyoutocompletetheexercisesgivenattheendofeachlesson.

AminimumMATLABsession

Thegoalofthisminimumsession(alsocalledstartingandexitingsessions)istolearnthefirststeps:

Howtologon

InvokeMATLAB

Doafewsimplecalculations

HowtoquitMATLAB

StartingMATLAB

Afterloggingintoyouraccount,youcanenterMATLABbydouble-clickingontheMATLABshortcuticon(MATLAB7.0.4)onyourWindowsdesktop.WhenyoustartMATLAB,aspecialwindowcalledtheMATLABdesktopappears.Thedesktopisawindowthatcontainsotherwindows.Themajortoolswithinoraccessiblefromthedesktopare:

TheCommandWindow

TheCommandHistory

TheWorkspace

TheCurrentDirectory

TheHelpBrowser

TheStartbutton

Figure1.1:ThegraphicalinterfacetotheMATLABworkspace

WhenMATLABisstartedforthefirsttime,thescreenlooksliketheonethatshownintheFigure1.1.ThisillustrationalsoshowsthedefaultconfigurationoftheMATLABdesktop.Youcancustomizethearrangementoftoolsanddocumentstosuityourneeds.

Now,weareinterestedindoingsomesimplecalculations.WewillassumethatyouhavesufficientunderstandingofyourcomputerunderwhichMATLABisbeingrun.

YouarenowfacedwiththeMATLABdesktoponyourcomputer,whichcontainstheprompt(>>)intheCommandWindow.Usually,thereare2typesofprompt:

>> forfullversion

EDU> foreducationalversion

Note:Tosimplifythenotation,wewillusethisprompt,>>,asastandardpromptsign,thoughourMATLABversionisforeducationalpurpose.

UsingMATLABasacalculator

Asanexampleofasimpleinteractivecalculation,justtypetheexpressionyouwanttoevaluate.Let’sstartattheverybeginning.Forexample,let’ssupposeyouwanttocalculatetheexpression,1+2×3.Youtypeitatthepromptcommand(>>)asfollows,

>>1+2*3

ans=

7

Youwillhavenoticedthatifyoudonotspecifyanoutputvariable,MATLABusesadefaultvariableans,shortforanswer,tostoretheresultsofthecurrentcalculation.Notethatthevariableansiscreated(oroverwritten,ifitisalreadyexisted).Toavoidthis,youmayassignavaluetoavariableoroutputargumentname.Forexample,

>>x=1+2*3

x=7

×

willresultinxbeinggiventhevalue1+23=7.Thisvariablenamecanalwaysbeusedtorefertotheresultsofthepreviouscomputations.Therefore,computing4xwillresultin

>>4*xans=

28.0000

Beforeweconcludethisminimumsession,Table1.1givesthepartiallistofarithmeticoperators.

Table1.1:Basicarithmeticoperators

Symbol Operation Example

+ Addition 2+3

? ?

Subtraction 2 3

? ?

Multiplication 2 3

/ Division 2/3

QuittingMATLAB

?→

ToendyourMATLABsession,typequitintheCommandWindow,orselectFile ExitMATLABinthedesktopmainmenu.

Gettingstarted

AfterlearningtheminimumMATLABsession,wewillnowlearntousesomeadditionaloperations.

CreatingMATLABvariables

MATLABvariablesarecreatedwithanassignmentstatement.Thesyntaxofvariableas-signmentis

variablename=avalue(oranexpression)

Forexample,

>>x=expression

whereexpressionisacombinationofnumericalvalues,mathematicaloperators,variables,andfunctioncalls.Onotherwords,expressioncaninvolve:

manualentry

built-infunctions

user-definedfunctions

Overwritingvariable

Onceavariablehasbeencreated,itcanbereassigned.Inaddition,ifyoudonotwishtoseetheintermediateresults,youcansuppressthenumericaloutputbyputtingasemicolon(;)attheendoftheline.Thenthesequenceofcommandslookslikethis:

>>t=5;

>>t=t+1

t =

6

Errormessages

Ifweenteranexpressionincorrectly,MATLABwillreturnanerrormessage.Forexample,inthefollowing,weleftoutthemultiplicationsign,*,inthefollowingexpression

>>x=10;

>>5x

???5x

|

Error:UnexpectedMATLABexpression.

Makingcorrections

Tomakecorrections,wecan,ofcourseretypetheexpressions.Butiftheexpressionislengthy,wemakemoremistakesbytypingasecondtime.Apreviouslytypedcommandcanberecalledwiththeup-arrowkey.Whenthecommandisdisplayedatthecommandprompt,itcanbemodifiedifneededandexecuted.

Controllingthehierarchyofoperationsorprecedence

Let’sconsiderthepreviousarithmeticoperation,butnowwewillincludeparentheses.Forexample,1+2×3willbecome(1+2)×3

>>(1+2)*3

ans =9

and,frompreviousexample

>>1+2*3

ans =7

Byaddingparentheses,thesetwoexpressionsgivedifferentresults:9and7.

× ×

TheorderinwhichMATLABperformsarithmeticoperationsisexactlythattaughtinhighschoolalgebracourses.Exponentiationsaredonefirst,followedbymultiplicationsanddivisions,andfinallybyadditionsandsubtractions.However,thestandardorderofprecedenceofarithmeticoperationscanbechangedbyinsertingparentheses.Forexample,theresultof1+23isquitedifferentthanthesimilarexpressionwithparentheses(1+2)3.Theresultsare7and9respectively.Parenthesescanalwaysbeusedtooverrulepriority,andtheiruseisrecommendedinsomecomplexexpressionstoavoidambiguity.

Therefore,tomaketheevaluationofexpressionsunambiguous,MATLABhasestab-lishedaseriesofrules.TheorderinwhichthearithmeticoperationsareevaluatedisgiveninTable1.2.MATLABarithmeticoperatorsobeythesameprecedencerulesasthosein

Table1.2:Hierarchyofarithmeticoperations

Precedence Mathematicaloperations

First Thecontentsofallparenthesesareevaluatedfirst,startingfromtheinnermostparenthesesandworkingoutward.

Second Allexponentialsareevaluated,workingfromlefttorightThird Allmultiplicationsanddivisionsareevaluated,working

fromlefttoright

Fourth Alladditionsandsubtractionsareevaluated,startingfromlefttoright

mostcomputerprograms.Foroperatorsofequalprecedence,evaluationisfromlefttoright.Now,consideranotherexample:

1 4 6

2+32+5×7

InMATLAB,itbecomes

>>1/(2+3^2)+4/5*6/7

ans=0.7766

or,ifparenthesesaremissing,

>>1/2+3^2+4/5*6/7

ans=10.1857

Soherewhatweget:twodifferentresults.Therefore,wewanttoemphasizetheimportanceofprecedenceruleinordertoavoidambiguity.

Controllingtheappearanceoffloatingpointnumber

?

MATLABbydefaultdisplaysonly4decimalsintheresultofthecalculations,forexample163.6667,asshowninaboveexamples.However,MATLABdoesnumericalcalculationsindoubleprecision,whichis15digits.Thecommandformatcontrolshowtheresultsofcomputationsaredisplayed.Herearesomeexamplesofthedifferentformatstogetherwith

theresultingoutputs.

>>formatshort

>>x=-163.6667

Ifwewanttoseeall15digits,weusethecommandformatlong

>>formatlong

>>x=-1.636666666666667e+002

Toreturntothestandardformat,enterformatshort,orsimplyformat.

Thereareseveralotherformats.Formoredetails,seetheMATLABdocumentation,ortypehelpformat.

Note-Uptonow,wehaveletMATLABrepeateverythingthatweenterattheprompt(>>).Sometimesthisisnotquiteuseful,inparticularwhentheoutputispagesenlength.TopreventMATLABfromechoingwhatwetype,simplyenterasemicolon(;)attheendofthecommand.Forexample,

>>x=-163.6667;

andthenaskaboutthevalueofxbytyping,

>>x

x =

-163.6667

Managingtheworkspace

Thecontentsoftheworkspacepersistbetweentheexecutionsofseparatecommands.There-fore,itispossiblefortheresultsofoneproblemtohaveaneffectonthenextone.Toavoidthispossibility,itisagoodideatoissueaclearcommandatthestartofeachnewinde-pendentcalculation.

>>clear

Thecommandclearorclearallremovesallvariablesfromtheworkspace.Thisfreesupsystemmemory.Inordertodisplayalistofthevariablescurrentlyinthememory,type

>>who

while,whoswillgivemoredetailswhichincludesize,spaceallocation,andclassofthevariables.

Keepingtrackofyourworksession

ItispossibletokeeptrackofeverythingdoneduringaMATLABsessionwiththediary

command.

>>diary

orgiveanametoacreatedfile,

>>diaryFileName

whereFileNamecouldbeanyarbitrarynameyouchoose.

ThefunctiondiaryisusefulifyouwanttosaveacompleteMATLABsession.TheysaveallinputandoutputastheyappearintheMATLABwindow.Whenyouwanttostoptherecording,enterdiaryoff.Ifyouwanttostartrecordingagain,enterdiaryon.Thefilethatiscreatedisasimpletextfile.Itcanbeopenedbyaneditororawordprocessingprogramandeditedtoremoveextraneousmaterial,ortoaddyourcomments.Youcanusethefunctiontypetoviewthediaryfileoryoucaneditinatexteditororprint.Thiscommandisuseful,forexampleintheprocessofpreparingahomeworkorlabsubmission.

Enteringmultiplestatementsperline

Itispossibletoentermultiplestatementsperline.Usecommas(,)orsemicolons(;)toentermorethanonestatementatonce.Commas(,)allowmultiplestatementsperlinewithoutsuppressingoutput.

>>a=7;b=cos(a),c=cosh(a)b =

0.6570

c =

548.3170

Miscellaneouscommands

Herearefewadditionalusefulcommands:

TocleartheCommandWindow,typeclc

ToabortaMATLABcomputation,typectrl-c

Tocontinuealine,type...

Gettinghelp

Toviewtheonlinedocumentation,selectMATLABHelpfromHelpmenuorMATLABHelpdirectlyintheCommandWindow.ThepreferredmethodistousetheHelpBrowser.TheHelpBrowsercanbestartedbyselectingthe?iconfromthedesktoptoolbar.Ontheotherhand,informationaboutanycommandisavailablebytyping

>>helpCommand

Anotherwaytogethelpistousethelookforcommand.Thelookforcommanddiffersfromthehelpcommand.Thehelpcommandsearchesforanexactfunctionnamematch,whilethelookforcommandsearchesthequicksummaryinformationineachfunctionforamatch.Forexample,supposethatwewerelookingforafunctiontotaketheinverseofamatrix.SinceMATLABdoesnothaveafunctionnamedinverse,thecommandhelpinversewillproducenothing.Ontheotherhand,thecommandlookforinversewillproducedetailedinformation,whichincludesthefunctionofinterest,inv.

>>lookforinverse

Note-Atthisparticulartimeofourstudy,itisimportanttoemphasizeonemainpoint.BecauseMATLABisahugeprogram;itisimpossibletocoverallthedetailsofeachfunctiononebyone.However,wewillgiveyouinformationhowtogethelp.Herearesomeexamples:

Useon-linehelptorequestinfoonaspecificfunction

>>helpsqrt

?

Inthecurrentversion(MATLABversion7),thedocfunctionopenstheon-lineversionofthehelpmanual.Thisisveryhelpfulformorecomplexcommands.

>>docplot

Uselookfortofindfunctionsbykeywords.Thegeneralformis

>>lookforFunctionName

Exercises

Note:DuetotheteachingclassduringthisFall2005,theproblemsaretemporarilyremovedfromthissection.

Chapter2

Tutoriallessons2

Mathematicalfunctions

MATLABoffersmanypredefinedmathematicalfunctionsfortechnicalcomputingwhichcontainsalargesetofmathematicalfunctions.

Typinghelpelfunandhelpspecfuncallsupfulllistsofelementaryandspecial

functionsrespectively.

ThereisalonglistofmathematicalfunctionsthatarebuiltintoMATLAB.Thesefunctionsarecalledbuilt-ins.Manystandardmathematicalfunctions,suchassin(x),cos(x),tan(x),ex,ln(x),areevaluatedbythefunctionssin,cos,tan,exp,andlogrespectivelyinMATLAB.

Table2.1listssomecommonlyusedfunctions,wherevariablesxandycanbenumbers,vectors,ormatrices.

Table2.1:Elementaryfunctions

cos(x)

Cosine

abs(x)

Absolutevalue

sin(x)

Sine

sign(x)

Signumfunction

tan(x)

Tangent

max(x)

Maximumvalue

acos(x)

Arccosine

min(x)

Minimumvalue

asin(x)atan(x)

exp(x)

Arcsine

ArctangentExponential

ceil(x)floor(x)

round(x)

Roundtowards+∞

Roundtowards?∞

Roundtonearestinteger

sqrt(x)

Squareroot

rem(x)

Remainderafterdivision

log(x)

Naturallogarithm

angle(x)

Phaseangle

log10(x)

Commonlogarithm

conj(x)

Complexconjugate

Inadditiontotheelementaryfunctions,MATLABincludesanumberofpredefined

constantvalues.AlistofthemostcommonvaluesisgiveninTable2.2.

pi Theπnumber,π=3.14159...

i,jTheimaginaryuniti,√?1

InfTheinfinity,∞

NaNNotanumber

Table2.2:Predefinedconstantvalues

Examples

Weillustrateheresometypicalexampleswhichrelatedtotheelementaryfunctionspreviouslydefined.

Asafirstexample,thevalueoftheexpressiony=e?asin(x)+10√y,fora=5,x=2,and

y=8iscomputedby

>>a=5;x=2;y=8;

>>y=exp(-a)*sin(x)+10*sqrt(y)y=

28.2904

Thesubsequentexamplesare

>>log(142)ans =

4.9558

>>log10(142)

ans =2.1523

Notethedifferencebetweenthenaturallogarithmlog(x)andthedecimallogarithm(base10)log10(x).

Tocalculatesin(π/4)ande10,weenterthefollowingcommandsinMATLAB,

>>sin(pi/4)ans =

0.7071

>>exp(10)ans =

2.2026e+004

Notes:

?

Onlyusebuilt-infunctionsontherighthandsideofanexpression.Reassigningthevaluetoabuilt-infunctioncancreateproblems.

?

Therearesomeexceptions.Forexample,iandjarepre-assignedto√1.However,

oneorbothofiorjareoftenusedasloopindices.

Toavoidanypossibleconfusion,itissuggestedtouseinsteadiiorjjasloopindices.

Basicplotting

overview

MATLABhasanexcellentsetofgraphictools.Plottingagivendatasetortheresultsofcomputationispossiblewithveryfewcommands.Youarehighlyencouragedtoplotmathematicalfunctionsandresultsofanalysisasoftenaspossible.Tryingtounderstandmathematicalequationswithgraphicsisanenjoyableandveryefficientwayoflearningmath-ematics.Beingabletoplotmathematicalfunctionsanddatafreelyisthemostimportantstep,andthissectioniswrittentoassistyoutodojustthat.

Creatingsimpleplots

ThebasicMATLABgraphingprocedure,forexamplein2D,istotakeavectorofx-coordinates,x=(x1,...,xN),andavectorofy-coordinates,y=(y1,...,yN),locatethepoints(xi,yi),withi=1,2,...,nandthenjointhembystraightlines.Youneedtopreparexandyinanidenticalarrayform;namely,xandyarebothrowarraysorcolumnarraysofthesamelength.

TheMATLABcommandtoplotagraphisplot(x,y).Thevectorsx=(1,2,3,4,5,6)andy=(3,?1,2,4,5,1)producethepictureshowninFigure2.1.

>>x=[123456];

>>y=[3-12451];

>>plot(x,y)

Note:Theplotfunctionshasdifferentformsdependingontheinputarguments.Ifyisavectorplot(y)producesapiecewiselineargraphoftheelementsofyversustheindexoftheelementsofy.Ifwespecifytwovectors,asmentionedabove,plot(x,y)producesagraphofyversusx.

Forexample,toplotthefunctionsin(x)ontheinterval[0,2π],wefirstcreateavectorofxvaluesrangingfrom0to2π,thencomputethesineofthesevalues,andfinallyplottheresult:

5

4

3

2

1

0

?1

1 2 3 4 5 6

Figure2.1:Plotforthevectorsxandy

>>x=0:pi/100:2*pi;

>>y=sin(x);

>>plot(x,y)

Notes:

0:pi/100:2*piyieldsavectorthat

startsa

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶(hù)所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶(hù)上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶(hù)上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶(hù)因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論