《MATLAB实验报告(8个实验).docx》由会员分享,可在线阅读,更多相关《MATLAB实验报告(8个实验).docx(26页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、MATLAB实验报告(8个实验)四川师范大学MATLAB语言实验报告1系级班年月日实验名称:Intro,Expressions,Commands姓名学号指导老师成绩1ObjectiveTheobjectiveofthislabistofamiliarizeyouwiththeMATLABprogramdevelopmentenvironmentandtodevelopyourfirstprogramsinthisenvironment.2UsingMATLAB2.1StartingMATLABLogontoyourcomputerandstartMATLABbydouble-clickingo
2、ntheicononthedesktoporbyusingtheStartProgramsmenu.MATLABDesktopwindowwillappearonthescreen.Thedesktopconsistsofseveralsub-windows.Themostimportantonesare:CommandWindow(ontherightsideoftheDesktop)isusedtodocalculations,entervariablesandrunbuilt-inandyourownfunctions.Workspace(ontheupperleftside)consi
3、stsofthesetofvariables(arrays)createdduringthecurrentMATLABsessionandstoredinmemory.CommandHistory(onthelowerleftside)logscommandsenteredintheCommandWindow.Youcanusethiswindowtoviewpreviouslyrunstatements,andcopyandexecuteselectedstatements.YoucanswitchbetweentheLaunchPadwindowandtheWorkspacewindowu
4、singthemenutabsunderthesub-windowontheupperleftside.Similarly,youcanswitchbetweentheCommandHistoryandCurrentDirectorywindowsusingthemenutabsunderthesub-windowonthelowerleftside.2.2ExecutingCommandsYoucantypeMATLABcommandsatthecommandprompt“ontheCommandWindow.Forexample,youcantypetheformulacos(/6)2si
5、n(3/8)as(cos(pi/6)2)*(sin(3*pi/8)Trythiscommand.Afteryoufinishtyping,pressenter.ThecommandwillbeinterpretedandtheresultwillbedisplayedontheCommandWindow.TrythefollowingbyobservinghowtheWorkspacewindowchanges:a=2;(Makenoteoftheusageof“;)b=3;c=a4?b?5+pi3Youcanseethevariablesa,bandcwiththeirtypesandsiz
6、esontheWorkspacewindow,andcanseethecommandsontheCommandHistorywindow.Spendafewminutestopracticedefiningarrayvariables(i.e.vectorsandmatrices)usingthesquarebracket(“)andcolon(“:)operators,andzeros()andones()functions.ar=12345;br=123;456;cr=1:3:15;?Setdrto?rst3elementsofar.dr=ar(1:3);?Setertosecondrow
7、ofbr.er=br(2,:);?Setartodrer.Findthenumberofelementsofar.ar=drer;length(ar)2.3GettingHelpThereareseveralwaystogethelponcommandsandfunctionsinMATLAB.FirstofallyoucanusetheHelpmenu.Youcanalsousethe“?button.Trytofindinformationontheplotfunctionfromthehelpindex.Alsotrytogetinformationonthesamefunctionus
8、ingthehelpcommand(i.e.typehelpplot).Finally,experimentwiththelookforcommand.Thiscommandlooksforothercommandsrelatedtoagivenkeyword.2.4SomeUsefulCommandsTrythefollowingcommandsandobservetheirresults:Which:VersionandlocationinfoClear:ClearstheworkspaceClc:Clearsthecommandwindowwho,whos:Listscontentoft
9、heworkspace3ExercisesPleasesolvethefollowingproblemsinMATLAB.Donotforgettokeepadiaryofyourcommandsandtheiroutputs. (1)De?nethevariablesxyandzas7.6,5.5and8.1,respectively,andevaluate:578.422.52?-xyxz(2)Computetheslopeofthelinethatpassesthroughthepoints(1,-2)and(5,8).(3)Quiz1.1:5 (4)1.6Exercises:1.1,1
10、.4(5)2.15Exercises:2.6,2.9,2.114QuittingMATLABTypingquitonthecommandwindowwillclosetheprogram.DonotforgettosendyourdiaryfileandM-filetoyourTA.Donotforgettodeleteyour?lesfromtheharddiskofthePCyouusedinthelabattheendofthelabsession.四川师范大学MATLAB语言实验报告2系级班年月日实验名称:Programming,RelationalandLogicalExpressi
11、ons姓名学号指导老师成绩1ObjectiveTheobjectiveofthislabistofamiliarizeyouwiththeMATLABscriptfiles(M-files),subarrays,relationalandlogicaloperators.2ScriptFilesScriptfilesarecollectionsofMATLABstatementsthatarestoredinafile.InsteadoftypingcommandsdirectlyintheCommandWindow,aseriesofcommandsmaybeplacedintoafilea
12、ndtheentirefilemaybeexecutedbytypingitsnameintheCommandWindow.SuchfilesarecalledscriptfilesthatarealsoknownasM-filesbecausetheyhaveanextensionof.m.Whenascriptfileisexecuted,theresultisthesameasitwouldbeifallofthecommandshadbeentypeddirectlyintotheCommandWindow.AllcommandsandscriptfilesexecutedintheC
13、ommandWindowshareacommonworkspace,sotheycanallsharevariablesintheworkspace.Notethatiftwoscriptfilesareexecutedsuccessively,thesecondscriptfilecanusethevariablescreatedbythefirstscriptfile.Inthisway,scriptfilescancommunicatewithotherscriptfilesthroughthedataleftbehindintheworkspace.AnEditWindowisused
14、tocreatenewM-filesortomodifyexistingones.TheEditWindowisaprogrammingtexteditor,withthefeaturesofMATLABlanguagehighlightedindifferentcolors.YoucancreateanewM-filewiththeFile/New/M-fileselectionandyoucanopenanexistingM-filewiththeFile/OpenselectionfromthedesktopmenuofMATLAB.(1)Createanewworkingdirecto
15、ryunderthecurrentdirectoryandchangethecurrentdirectorytoTA?ssuggest?.3SubarraysItispossibletoselectandusesubsetsofMATLABarrays.Toselectasubsetofanarray,justincludealistoftheelementstobeselectedintheparenthesesafterthearrayname.MATLABhasaspecialfunctionnamedendthatisusedtocreatearraysubscripts.Theend
16、functionalwaysreturnsthehighestvaluetakenonbyagivensubscript.Itisalsopossibletousesubarraysontheleft-handsideofanassignmentstatementtochangeonlysomeofthevaluesinanarray.Ifvaluesareassignedtoasubarray,onlythosevaluesarechangedbutifvaluesareassignedtoanarray,theentirecontentsofthearrayarereplacedbythe
17、newvalues.(1)Definethefollowing5x5arrayarr1inMATLAB.?-=2274235421209518171651413215111012844563311arr(2)WriteaMATLABstatementtoselectasubsetofarr1andreturnthesubarraycontainingthevaluesasshown.?=22745456311arrarr11=arr1(1,5,245);(3)WritetwoMATLABstatementstoselectthelastrowandlastcolumnofarr1,separa
18、tely.arr12=arr1(5,:);或arr12=arr1(end,:);arr13=arr1(:,end);或arr13=arr1(:,5);(4)WriteMATLABstatementstoobtainthefollowingarrayfromarr1.?-=2257462335432112arrarr2=arr1(15,:);4RelationalandLogicalOperatorsRelationalandlogicaloperatorsarethetwotypesofoperatorsthatproducetrue/falseresultsinMATLABprograms.
19、MATLABinterpretsazerovalueasfalseandanynonzerovalueastrue.Relationaloperators(=,=,=,beforeotherlogicoperators. (1)Definethefollowing4x5arrayarr4inMATLAB.?-=212343212343212543214arr(2)Writeanexpressionusingarr4andarelationaloperatortoproducethefollowingresult.?=110001110011110111115arrarr5=arr40;(3)W
20、riteanexpressionusingarr4andarelationaloperatortoproducethefollowingresult.?=010000010000010000016arrarr6=arr4=1;(4)WriteaMATLABprogramwhichwillgeneratean(n-1)x(n-1)matrixfromagivennxnmatrixwhichwillbeequaltogivenmatrixwithfirstrowandfirstcolumndeleted.arr44=rand(5);arr444=arr35(2:end,2:end);(5)Gene
21、ralizeyourprogramabovesothattheprogramshouldasktherowandcolumnnumberstobedeletedandthengeneratenew(n-1)x(n-1)matrix.n=input(inputn:);matrixn=rand(n)delrow=input(inputrownumberstobedeleted:);delcolumn=input(inputcolumnnumberstobedeleted:);matrixn_1=matrixn(1:delrow-1delrow+1:end,1:delcolumn-1delcolum
22、n+1:end)(6)Quiz3.1P885QuittingMATLABTypingquitonthecommandwindowwillclosetheprogram.DonotforgettosendyourdiaryfileandM-filetoyourTA.DonotforgettodeleteyourfilesfromtheharddiskofthePCyouusedinthelabattheendofthelabsession.四川师范大学MATLAB语言实验报告3系级班年月日实验名称:BranchesandLoops,LogicalArrays.姓名学号指导老师成绩1Objecti
23、veTheobjectiveofthislabistofamiliarizeyouwiththeMATLABBranchesandLoops,LogicalArrays.2ExercisesDonotforgettoaddsufficientdocumentationandproperindentationtoallprogramsyouwrite.(1)Writeaprogramthatcalculatesfollowequationwithforandwhileloop,andwriteaprogramwithoutloop.63263022212+=iiK%forloopk1=0;for
24、ii=1:64k1=k1+2(ii-1);end%whileloopk2=0;n=0;whilen=0&nEnteravectorofintegers:1328056Thenumberofmultiplesof3is2(3)Therootmeansquareisawayforcalculatingameanforasetofnumbers.Thermsaverageofaseriesofnumbersisgivenas:=NiixNrmsaverage121Writeaprogramthatwillacceptanarbitrarynumberofinputvaluesandcalculate
25、thermsaverageofthenumbers.Theprogramshouldasktheuserforthenumberofvaluestobeentered.Testyourprogramwith4and10setofnumbers.%Therootmeansquareisawayforcalculatingameanforasetofnumbers%Initializesum_x2=0;%Getthenumberofpointstoinput.n=input(Enternumberofpoints:);%Looptoreadinputvaluesforii=1:n%Readinne
26、xtvaluex=input(Entervalue:);%Calculatesquaresumssum_x2=sum_x2+x2;end%Nowcalculaterootmeansquareroot_ms=sqrt(sum_x2/n);%Telluserfprintf(Thenumberofdatapointsis:%dn,n);fprintf(Therootmeansquareofthisdatasetis:%fn,root_ms); (4)3.8exercises:3.5(5)4.7Exercises:4.14.23QuittingMATLABTypingquitonthecommandw
27、indowwillclosetheprogram.DonotforgettosendyourM-filetoyourTA.DonotforgettodeleteyourfilesfromtheharddiskofthePCyouusedinthelabattheendofthelabsession.四川师范大学MATLAB语言实验报告4系级班年月日实验名称:MATLAB/SIMULINKpackage姓名学号指导老师成绩1ObjectiveTolearnhowtouseMATLAB/SIMULINKpackageTolearnhowtoestimateperformanceparameters
28、fromtime-domaindata2SIMULINKBasicBasicsteps(1)ClickontheMATLABbuttontostartMATLAB.(2)OnceMATLABhasstartedup,typesimulink(SMALLLETTERS!)attheMATLABprompt()followedbyacarriagereturn(pressthereturnkey).ASIMULINKwindowshouldappearshortly,withthefollowingicons:Sources,Sinks,Discrete,Linear,Connections,Ex
29、tras.(3)Next,gototheFilemenuinSIMULINKwindowandchooseNewinordertobeginbuildingtheblockdiagramrepresentationofthesystemofinterest.(4)Openoneormoreoftheblocklibrariesanddragthechosenblocksintotheactive.(5)Aftertheblocksareplaced,drawlinestoconnecttheirinputandoutputportsbymovingthemouseoveraportanddra
30、gusingtheleftbutton.Tomakealinewitharightangleinit,releasethebuttonwhereyouwantthecorner,thenclickontheendofthelineanddragtocreatenextsegment.Toaddasecondlinethatrunsoffofanexistinglineclicktherightmouseonanexistinglineanddragit.(6)SavethesystembyselectingSavefromtheFilemenu.(7)Opentheblocksbydouble
31、-clickingandchangesomeoftheirinternalparameters.(8)AdjustsomesimulationparametersbyselectingParametersfromtheSimulationmenu.ThemostcommonparametertochangeisStopTimethatdefinesthelengthoftimethesimulationwillrun.(9)RunthesimulationbyselectingStartfromtheSimulationmenu.Youcanstopasimulationbeforecompl
32、etingbyselectingStopfromtheSimulationmenu.(10)ViewthebehaviorofthesystembyattachingScopeblockstothevariablesofinterest,orbyusingToWorkspaceblockstosenddatatotheMATLABworkspacewhereyoucanplottheresultsusingstandardMATLABcommands.3Exercises(1)YourTAhasshownyouhowtoobserveandprintsignalsfromthescope.Tr
33、ythisoutbyprintingouttheinputsignal,whichshouldbea-1Vto1Vsquarewavewithfrequency0.1Hz.Notethepeak-to-peakvoltagedifferenceofthissignal.Notetowritekeyblocksparameters.(2)WriteaSimulinkmodeltocalculatethefollowingdifferentialequation,0)1(222=+-xdtdxxdtxdInitialized1)0(=x,0)0(=dtdx。(3)Anopen-loopcontro
34、lsystemisasfollowing:11)(+=ssPSetthecontrollergainK=10.Simulatethesystemandexaminethestepresponseoftheclosedloopsystemusinganinputstepsizeof2.0(changethestepsizebydouble-clickingontheStepFcnblock).ViewthecontrolleroutputuandoutputybyScopeblocks,andplotoutputvs.timeinMATLABworkspace.UseaTransferFcnbl
35、ockfortheplant.Todesignthecontroller,useaGainblockfortheproportionalcontrolblock,andaStepFcnblockfortheinput.TieScopeblockstothecontrolleroutput(plantinput)andplantoutput.InordertobringthevariablesintotheMATLABworkspace,tieToWorkspaceblockstotimefromtheClockblock,andtheoutputy.Makethestepoccuratt=1.
36、0second.DoubleclickToWorkspaceblock,andset“Saveformatto“Array.Library:StepSourcesGainMathTransferFcnContinuousScopeSinksToWorkspaceSinksClockSources4QuittingMATLABTypingquitonthecommandwindowwillclosetheprogram.DonotforgettosendyourM-filetoyourTA.DonotforgettodeleteyourfilesfromtheharddiskofthePCyou
37、usedinthelabattheendofthelabsession.四川师范大学MATLAB语言实验报告5系级班年月日实验名称:plottingControllerPlant姓名学号指导老师成绩1ObjectiveLearnhowtouseMATLAB2DplotslearnhowtouseMatlabdemoslearnhowtouse3Dsurfaceplotshavefun22DPlottingandrand/roundfunctions.(1)Createa10x10randommatrixwithvalue0,1usingrand.Callthismatrixz.(2)Compu
38、teandplotsumofallcolumns.Thisshouldresultinoneplotline.Thexaxisshouldbecolumnnumber,andtheyaxisisthesumofeachsinglecolumn.(3)Applyroundtothematrix,andthenplotthesumoftheresultingmatrix.(4)Applyceiltothematrix,andthenplotthesumoftheresultingmatrix.(5)Applyfloortothematrix,andthenplotthesumoftheresult
39、ingmatrix.Putalloftheseplotsonthesamegraph(therewillbeatotaloffourlines),witheachlineadifferentcolorand/orpattern.Makesuretocreatealegendidentifyingeachline.Alsoputatitleandaxeslabelsonthegraph.SavethisscripttocopytotheTAattheendofthelab.3Matlabdemos2DPlotting,3DSurfacePlotting.Nowletslearnhowtoplot
40、.Atthesametime,weregoingtolearnhowtouseMatlabdemos.YoucanuseMatlabdemoswheneveryouwanttolearnmoreaboutaparticularfeature.FindthedemounderMATLAB-Graphics-2-DPlotsand3-DPlots.ReadthedescriptionandclickonRunthisdemo.Playwiththedifferentoptions,andlookatthecodeusedtogenerateeachplot(intheminicommandwind
41、owaspartofthedemo).Youwanttobeabletousewhatyouvelearnedfromthisdemo.Tryplottingonestyleofgraphonyourown,byputtingitinascriptfileandexecutingthecommands.43DSurfacePlotting.Inthedemoyoulookedatabove,ademofunctioncalledpeakswasusedtogetthedataforthe3Dsurfaceplot.Thismatrixstoresthezvalues(heightvalues)
42、forthexandydimensions.Whenyouplotit,ifyoudonotspecifyxandyvalues,itmakesassumptionsaboutthevaluesofthexandyaxes(namely,theystartat1andgoupby1fortheentirelengthofthematrix).Wearegoingtomakeourown3Dsurfaceplot,butusingourowndata.Usingthe10x10randommatrixyougeneratedatthebeginningofthelab,makea3Dsurfac
43、eplot.Ifyourmatrixwithrandomvaluesisnamedz,youcancreatethisplotbyusingthecommandsurf(z).Changetheshadingandthecolormapofthisplot,andstorethecommandsinanm-filetocopytheTAattheend.Now,letssaywedontlikethedefaultsettingofthexandyaxesas1:10.Wewantourxvaluestobe16to25,andouryvaluestobe111to120,.Wecantjus
44、tusethesex=16:25andy=111:120valuesinsurfdirectly.Nowusemeshgridtocreatethexandymatricesappropriatetouseinsurf(x,y,z)fortheplotwiththestateddesiredaxes.Plotthisdataonanewfigure,andsavethecodetocopyTAattheendofthelab.5Morefunwith3Dsurfaceplots.Usethisdata:X,Y=meshgrid(-8:.5:8);R=sqrt(X.2+Y.2)+eps;Z=si
45、n(R)./R;mesh(X,Y,Z)%similartosurfWhatwillhappenifyouplotthesamething,butchangeZto-Z?Convinceyourselfofwhatwillhappenwhenyoudothis,andthentryitout.Savethisinascriptandthenmanipulatetheplottomakeithaveasmooth(non-gridded)surfacecoloreddifferentlythanitisnow.6QuittingMATLABNote:Payattentiontotheunderli
46、nedtext-youwillhavetocopythesethingstoTAattheendofthelab.Typingquitonthecommandwindowwillclosetheprogram.DonotforgettodeleteyourfilesfromtheharddiskofthePCyouusedinthelabattheendofthelabsession.四川师范大学MATLAB语言实验报告6系级班年月日实验名称:User-Definedfunctions,andInput&Outputfunctions姓名学号指导老师成绩1ObjectiveTheobjectiveofthislabistofamiliarizeyouwiththeMATLABUser-Definedfunctions,andInput&Outputfunctions.2User-Definedfunctions(1)RandomNumbersa.Writeafunctionthatgeneratesarandomintegerintherangea,bgivenbytheuser.