INTRODUCTION TO MATLAB FOR ENGINEERING STUDENTS 面向工程专业学生的 MATLAB 简介_第1页
INTRODUCTION TO MATLAB FOR ENGINEERING STUDENTS 面向工程专业学生的 MATLAB 简介_第2页
INTRODUCTION TO MATLAB FOR ENGINEERING STUDENTS 面向工程专业学生的 MATLAB 简介_第3页
INTRODUCTION TO MATLAB FOR ENGINEERING STUDENTS 面向工程专业学生的 MATLAB 简介_第4页
INTRODUCTION TO MATLAB FOR ENGINEERING STUDENTS 面向工程专业学生的 MATLAB 简介_第5页
已阅读5页,还剩69页未读, 继续免费阅读

付费下载

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

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“learningbydoing”.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“learningbydoing”.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. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论