Chapter 2

73
Interactive Computing with Matlab Gerald W. Recktenwald Department of Mechanical Engineering These slides are a supplement to the book Numerical Methods with Matlab: Implementations and Applications, by Gerald W. Recktenwald, c 2000, Prentice-Hall, Upper Saddle River, NJ. These slides are c 2000 Gerald W. Recktenwald. My intention is that the slides will be helpful for instructors using Numerical Methods with Matlab as a textbook for their course. The slides may be downloaded or stored or printed only for noncommercial, educational use. The repackaging and sale of these slides in any form is expressly prohibited. The latest version of this PDF file, along with other supplemental material for the book Version 1.0 August 16, 2000

description

matlap

Transcript of Chapter 2

InteractiveComputingwithMatlabGeraldW.RecktenwaldDepartmentofMechanicalEngineeringThese slides are a supplement to the book Numerical Methods withMatlab: Implementations and Applications, by Gerald W. Recktenwald,c 2000, Prentice-Hall, Upper Saddle River, NJ. These slides are c 2000GeraldW.Recktenwald.My intention is that the slides will be helpful for instructors usingNumerical MethodswithMatlabasatextbookfortheircourse. Theslidesmaybedownloadedorstoredorprintedonlyfornoncommercial,educationaluse.The repackaging and sale of these slides in any formis expresslyprohibited.The latest version of this PDF le, along with other supplemental materialforthebookVersion1.0 August16,2000Overview BasicMatlabOperations StartingMatlab UsingMatlabasacalculator Introductiontovariablesandfunctions MatricesandVectors: Allvariablesarematrices. Creatingmatricesandvectors Subscriptnotation Colonnotation AdditionalTypesofVariables Complexnumbers Strings Polynomials WorkingwithMatricesandVectors Linearalgebra Vectorizedoperations Arrayoperators ManagingtheInteractiveEnvironment PlottingNMM:InteractiveComputingwithMatlab page1StartingMatlab DoubleclickontheMatlabicon,oronunixsystemstypematlabatthecommandline. AfterstartupMatlabdisplaysacommandwindowthatisusedtoentercommandsanddisplaytext-onlyresults. EnterCommandsatthecommandprompt:>> forfullversionEDU> foreducationalversion Matlabrespondstocommandsbyprintingtextinthecommandwindow,orbyopeningagurewindowforgraphicaloutput. Togglebetweenwindowsbyclickingonthemwiththemouse.NMM:InteractiveComputingwithMatlab page2MatlabWindows(version5)Command WindowHelpwin WindowPlot WindowNMM:InteractiveComputingwithMatlab page3MatlabasaCalculatorWorkdirectlywithnumbers>> 2 + 6 - 4 (pressreturn after 4)ans =4>> ans/2ans =2Or,deneandusevariables>> a = 5a =5>> b = 6b =6>> c = b/ac =1.2000NMM:InteractiveComputingwithMatlab page4Built-inVariablespi(=)andansareabuilt-invariables>> pians =3.1416>> sin(ans/4)ans =0.7071Note: Thereisnodegreesmode. Allanglesaremeasuredinradians.NMM:InteractiveComputingwithMatlab page5Built-inFunctionsManystandardmathematicalfunctions,suchassin,cos,log,andlog10,arebuilt-in>> log(256)ans =5.5452>> log10(256)ans =2.4082>> log2(256)ans =8NMM:InteractiveComputingwithMatlab page6LookingforFunctionsSyntax:lookfor stringsearchesrstlineoffunctiondescriptionsforstring.Example:>> lookfor cosineproducesACOS Inverse cosine.ACOSH Inverse hyperbolic cosine.COS Cosine.COSH Hyperbolic cosine.NMM:InteractiveComputingwithMatlab page7WaystoGetHelp Useon-linehelptorequestinfoonaspecicfunction>> help sqrt Thehelpwinfunctionopensaseparatewindowforthehelpbrowser>> helpwin(sqrt) Uselookfortondfunctionsbykeywords>> lookfor functionNameNMM:InteractiveComputingwithMatlab page8On-lineHelpSyntax:help functionNameExample:>> help logproducesLOG Natural logarithm.LOG(X) is the natural logarithm of the elements of X.Complex results are produced if X is not positive.See also LOG2, LOG10, EXP, LOGM.NMM:InteractiveComputingwithMatlab page9SuppressOutputwithSemicolonResultsofintermediatestepscanbesuppressedwithsemicolons.Example: Assignvaluestox,y,andz,butonlydisplaythevalueof zinthecommandwindow:>> x = 5;>> y = sqrt(59);>> z = log(y) + x^0.25z =3.5341Typevariablenameandomitthesemicolontoprintthevalueofavariable(thatisalreadydened)>> yy =7.6811 ( = log(sqrt(59)) + 5^0.25 )NMM:InteractiveComputingwithMatlab page10MultipleStatementsperLineUsecommasorsemicolonstoentermorethanonestatementatonce. Commasallowmultiplestatementsperlinewithoutsuppressingoutput.>> a = 5; b = sin(a), c = cosh(a)b =-0.9589c =74.2099NMM:InteractiveComputingwithMatlab page11MatlabVariablesNamesLegal variablenames: BeginwithoneofazorAZ Haveremainingcharacterschosenfromaz,AZ,09,or Haveamaximumlengthof31characters Shouldnotbethenameofabuilt-invariable,built-infunction,oruser-denedfunctionExamples:xxxxxxxxxpipeRadiuswidgets_per_baubblemySummysumNote: mySumandmysumaredierentvariables. Matlabiscasesensitive.NMM:InteractiveComputingwithMatlab page12Built-inMatlabVariablesName Meaningans valueofanexpressionwhenthatexpressionisnotassignedtoavariableeps oatingpointprecisionpi , (3.141492 . . . )realmax largestpositiveoatingpointnumberrealmin smallestpositiveoatingpointnumberInf ,anumberlargerthanrealmax,theresultofevaluating1/0.NaN notanumber,theresultofevaluating0/0Rule: Onlyusebuilt-invariablesontherighthandsideofanexpression. Reassigningthevalueofabuilt-invariablecancreateproblemswithbuilt-infunctions.Exception: iand jarepreassignedto1. Oneorbothofiorjareoftenreassignedasloopindices. MoreonthislaterNMM:InteractiveComputingwithMatlab page13MatricesandVectorsAllMatlabvariablesarematricesAMatlabvectorisamatrixwithoneroworonecolumnAMatlabscalarisamatrixwithonerowandonecolumnOverviewofWorkingwithmatricesandvectors Creatingvectors:linspaceandlogspace Creatingmatrices:ones,zeros,eye,diag. . . Subscriptnotation Colonnotation VectorizationNMM:InteractiveComputingwithMatlab page14CreatingMatlabVariablesMatlabvariablesarecreatedwithanassignmentstatement>> x = expressionwhereexpressionisavalidMatlabexpressionthatevaluatestoamatrix,vectororscalar.Theexpressioncaninvolve: Manualentry Built-infunctionsthatreturnmatrices Custom(user-written)functionsthatreturnmatrices LoadingmatricesfromtextlesormatlesNMM:InteractiveComputingwithMatlab page15Manual EntryFormanualentry,theelementsinavectorareenclosedinsquarebrackets. Whencreatingarowvector,separateelementswithaspace.>> v = [7 3 9]v =7 3 9Separatecolumnswithasemicolon>> w = [2; 6; 1]w =261Inamatrix,rowelementsareseparatedbyspaces,andcolumnsareseparatedbysemicolons>> A = [1 2 3; 5 7 11; 13 17 19]A =1 2 35 7 1113 17 19NMM:InteractiveComputingwithMatlab page16TransposeOperatorOnceitiscreated,avariablecanbetransformedwithotheroperators. Thetransposeoperator convertsarowvectortoacolumnvector(andviceversa),anditchangestherowsofamatrixtocolumns.>> v = [2 4 1 7]v =2 4 1 7>> vans =2417>> A = [1 2 3; 4 5 6; 7 8 9 ]A =1 2 34 5 67 8 9>> Aans =1 4 72 5 83 6 9NMM:InteractiveComputingwithMatlab page17OverwritingVariablesOnceavariablehasbeencreated,itcanbereassigned>> x = 2;>> x = x + 2x =4>> y = [1 2 3 4]y =1 2 3 4>> y = yy =1234NMM:InteractiveComputingwithMatlab page18CreatingvectorswithlinspaceThelinspacefunctioncreatesvectorswithelementshavinguniformlinearspacing.Syntax:x = linspace(startValue,endValue)x = linspace(startValue,endValue,nelements)Examples:>> u = linspace(0.0,0.25,5)u =0 0.0625 0.1250 0.1875 0.2500>> u = linspace(0.0,0.25);>> v = linspace(0,9,4)v =0369Note: ColumnvectorsarecreatedbyappendingthetransposeoperatortolinspaceNMM:InteractiveComputingwithMatlab page19Example: ATableofTrigFunctions>> x = linspace(0,2*pi,6); (note transpose)>> y = sin(x);>> z = cos(x);>> [x y z]ans =0 0 1.00001.2566 0.9511 0.30902.5133 0.5878 -0.80903.7699 -0.5878 -0.80905.0265 -0.9511 0.30906.2832 0 1.0000Theexpressionsy = sin(x)andz = cos(x)takeadvantageofvectorization. Iftheinputtoavectorizedfunctionisavectorormatrix,theoutputisoftenavectorormatrixhavingthesameshape. Moreonthislater.NMM:InteractiveComputingwithMatlab page20CreatingvectorswithlogspaceThelogspacefunctioncreatesvectorswithelementshavinguniformlogarithmicspacing.Syntax:x = logspace(startValue,endValue)x = logspace(startValue,endValue,nelements)createsnelementselementsbetween10startValueand10endValue.Thedefaultvalueofnelementsis100.Example:>> w = logspace(1,4,4)w =10 100 1000 10000NMM:InteractiveComputingwithMatlab page21FunctionstoCreateMatrices(1)Name Operation(s)Performeddiag create a matrix with a specied diagonal entries,orextractdiagonalentriesofamatrixeye createanidentitymatrixones createamatrixlledwithonesrand createamatrixlledwithrandomnumberszeros createamatrixlledwithzeroslinspace createarowvectoroflinearlyspacedelementslogspace create a rowvector of logarithmically spacedelementsNMM:InteractiveComputingwithMatlab page22FunctionstoCreateMatrices(2)Useonesandzerostosetintialvaluesofamatrixorvector.Syntax:A = ones(nrows,ncols)A = zeros(nrows,ncols)Examples:>> D = ones(3,3)D =1 1 11 1 11 1 1>> E = ones(2,4)E =0 0 0 00 0 0 0NMM:InteractiveComputingwithMatlab page23FunctionstoCreateMatrices(3)onesandzerosarealsousedtocreatevectors. Todoso,seteithernrowsorncolsto1.>> s = ones(1,4)s =1 1 1 1>> t = zeros(3,1)t =000NMM:InteractiveComputingwithMatlab page24FunctionstoCreateMatrices(4)Theeyefunctioncreatesidentitymatricesofaspeciedsize. Itcanalsocreatenon-squarematriceswithonesonthemaindiagonal.Syntax:A = eye(n)A = eye(nrows,ncols)Examples:>> C = eye(5)C =1 0 0 0 00 1 0 0 00 0 1 0 00 0 0 1 00 0 0 0 1>> D = eye(3,5)D =1 0 0 0 00 1 0 0 00 0 1 0 0NMM:InteractiveComputingwithMatlab page25FunctionstoCreateMatrices(5)Thediagfunctioncaneither createamatrixwithspecieddiagonalelements,or extractthediagonalelementsfromamatrixSyntax:A = diag(v)v = diag(A)Example: Usediagtocreateamatrix>> v = [1 2 3];>> A = diag(v)A =1 0 00 2 00 0 3NMM:InteractiveComputingwithMatlab page26FunctionstoCreateMatrices(6)Example: Usediagtoextractthediagonalofamatrix>> B = [1:4; 5:8; 9:12]B =1 2 3 45 6 7 89 10 11 12>> w = diag(B)w =1611Note: Theactionofthediagfunctiondependsonthecharacteristicsandnumberoftheinput(s). ThispolymorphicbehaviorofMatlabfunctionsiscommon. Theon-linedocumentation(help diag)explainsthepossiblevariations.NMM:InteractiveComputingwithMatlab page27SubscriptNotation(1)If Aisamatrix,A(i,j)selectstheelementintheithrowandjthcolumn. Subscriptnotationcanbeusedontherighthandsideofanexpressiontorefertoamatrixelement.>> A = [1 2 3; 4 5 6; 7 8 9];>> b = A(3,2)b =8>> c = A(1,1)c =1Subscriptnotationisalsousedtoassignmatrixelements>> A(1,1) = c/bA =0.2500 2.0000 3.00004.0000 5.0000 6.00007.0000 8.0000 9.0000NMM:InteractiveComputingwithMatlab page28SubscriptNotation(2)Referringtoelementsoutsideofcurrentmatrixdimensionsresultsinanerror>> A = [1 2 3; 4 5 6; 7 8 9];>> A(1,4)??? Index exceeds matrix dimensions.Assigninganelementsoutsideofcurrentmatrixdimensionscausesthematrixtoberesized!>> A = [1 2 3; 4 5 6; 7 8 9];A =1 2 34 5 67 8 9>> A(4,4) = 11A =1 2 3 04 5 6 07 8 9 00 0 0 11Matlabautomaticallyresizesmatricesonthey.NMM:InteractiveComputingwithMatlab page29ColonNotation(1)ColonnotationisverypowerfulandveryimportantintheeectiveuseofMatlab. Thecolonisusedasbothanoperatorandasawildcard.Usecolonnotationto: createvectors refertoorextractrangesofmatrixelementsSyntax:startValue:endValuestartValue:increment:endValueNote: startValue,increment,andendValuedonotneedtobeintegersNMM:InteractiveComputingwithMatlab page30ColonNotation(2)Creatingrowvectors:>> s = 1:4s =1 2 3 4>> t = 0:0.1:0.4t =0 0.1000 0.2000 0.3000 0.4000Creatingcolumnvectors:>> u = (1:5)u =12345>> v = 1:5v =1 2 3 4 5visarowvectorbecause1:5createsavectorbetween1andthetransposeof5.NMM:InteractiveComputingwithMatlab page31ColonNotation(3)Usecolonasawildcardtorefertoanentirecolumnorrow>> A = [1 2 3; 4 5 6; 7 8 9];>> A(:,1)ans =147>> A(2,:)ans =4 5 6Orusecolonnotationtorefertosubsetsofcolumnsorrows>> A(2:3,1)ans =47>> A(1:2,2:3)ans =ans =2 35 6NMM:InteractiveComputingwithMatlab page32ColonNotation(4)Colonnotationisoftenusedincompactexpressionstoobtainresultsthatwouldotherwiserequireseveralsteps.Example:>> A = ones(8,8);>> A(3:6,3:6) = zeros(4,4)A =1 1 1 1 1 1 1 11 1 1 1 1 1 1 11 1 0 0 0 0 1 11 1 0 0 0 0 1 11 1 0 0 0 0 1 11 1 0 0 0 0 1 11 1 1 1 1 1 1 11 1 1 1 1 1 1 1NMM:InteractiveComputingwithMatlab page33ColonNotation(5)Finally,colonnotationisusedtoconvertanyvectorormatrixtoacolumnvector.Examples:>> x = 1:4;>> y = x(:)y =1234>> A = rand(2,3);>> v = A(:)v =0.95010.23110.60680.48600.89130.76210.4565Note: Therandfunctiongeneratesrandomelementsbetweenzeroandone. Repeatingtheprecedingstatementswill,inalllikelihood,producedierentnumericalvaluesfortheelementsof v.NMM:InteractiveComputingwithMatlab page34Additional TypesofVariablesThebasicMatlabvariableisamatrixatwodimensionalarrayofvalues. Theelementsofamatrixvariablecaneitherbenumericvaluesorcharacters. Iftheelementsarenumericvaluestheycaneitherberealorcomplex(imaginary).Moregeneralvariabletypesareavailable: n-dimensionalarrays(wheren>2),structs,cellarrays,andobjects. Numeric(realandcomplex)andstringarraysofdimensiontwoorlesswillbesucientforourpurposes.Wenowconsidersomesimplevariationsonnumericandstringmatrices: ComplexNumbers Strings PolynomialsNMM:InteractiveComputingwithMatlab page35ComplexNumbersMatlabautomaticallyperformscomplexarithmetic>> sqrt(-4)ans =0 + 2.0000i>> x = 1 + 2*i (or, x = 1 + 2*j)x =1.0000 + 2.0000i>> y = 1 - 2*iy =1.0000 - 2.0000i>> z = x*yz =5NMM:InteractiveComputingwithMatlab page36UnitImaginaryNumbersiandjareordinaryMatlabvariablesthathavebepreassignedthevalue1.>> i^2ans =-1Bothoreitheriandjcanbereassigned>> i = 5;>> t = 8;>> u = sqrt(i-t) (i-t = -3, not -8+i)u =0 + 1.7321i>> u*uans =-3.0000>> A = [1 2; 3 4];>> i = 2;>> A(i,i) = 1A =1 23 1NMM:InteractiveComputingwithMatlab page37EulerNotation(1)Eulernotationrepresentsacomplexnumberbyaphaserz=eix=Re(z)= |z| cos()= cos()y=iIm(z)=i|z| sin()=i sin()realimaginaryxiy z = eiNMM:InteractiveComputingwithMatlab page38FunctionsforComplexArithmetic(1)Function Operationabs Computethemagnitudeofanumberabs(z)isequivalenttotosqrt( real(z)^2 + imag(z)^2 )angle AngleofcomplexnumberinEulernotationexp If xisreal,exp(x)=exIf ziscomplex,exp(z)=eRe(z)(cos(Im(z) + i sin(Im(z))conj Complexconjugateofanumberimag Extracttheimaginarypartofacomplexnumberreal ExtracttherealpartofacomplexnumberNote: Whenworkingwithcomplexnumbers,itisagoodideatoreserveeitheriorjfortheunitimaginaryvalue1.NMM:InteractiveComputingwithMatlab page39FunctionsforComplexArithmetic(2)Examples:>> zeta = 5; theta = pi/3;>> z = zeta*exp(i*theta)z =2.5000 + 4.3301i>> abs(z)ans =5>> sqrt(z*conj(z))ans =5>> x = real(z)x =2.5000>> y = imag(z)y =4.3301>> angle(z)*180/pians =60.0000Remember: ThereisnodegreesmodeinMatlab. Allanglesaremeasuredinradians.NMM:InteractiveComputingwithMatlab page40Strings Stringsarematriceswithcharacterelements. Stringconstantsareenclosedinsinglequotes ColonnotationandsubscriptoperationsapplyExamples:>> first = John;>> last = Coltrane;>> name = [first, ,last]name =John Coltrane>> length(name)ans =13>> name(9:13)ans =traneNMM:InteractiveComputingwithMatlab page41FunctionsforStringManipulation(1)Function Operationchar convertanintegertothecharacterusingASCIIcodes,orcombinecharactersintoacharactermatrixfindstr ndsonestringinanotherstringlength returnsthenumberofcharactersinastringnum2str convertsanumbertostringstr2num convertsastringtoanumberstrcmp comparestwostringsstrmatch identiesrowsofacharacterarraythatbeginwithastringstrncmp comparestherstnelementsoftwostringssprintf convertsstringsandnumericvaluestoastringNMM:InteractiveComputingwithMatlab page42FunctionsforStringManipulation(2)Examples:>> msg1 = [There are ,num2str(100/2.54), inches in a meter]message1 =There are 39.3701 inches in a meter>> msg2 = sprintf(There are %5.2f cubic inches in a liter,1000/2.54^3)message2 =There are 61.02 cubic inches in a liter>> both = char(msg1,msg2)both =There are 39.3701 inches in a meterThere are 61.02 cubic inches in a liter>> strcmp(msg1,msg2)ans =0>> strncmp(msg1,msg2,9)ans =1>> findstr(in,msg1)ans =19 26NMM:InteractiveComputingwithMatlab page43PolynomialsMatlabpolynomialsarestoredasvectorsofcoecients. ThepolynomialcoecientsarestoredindecreasingpowersofxPn(x)=c1xn+ c2xn1+. . . + cnx + cn+1Example: Evaluatex32x + 12atx= 1.5>> c = [1 0 -2 12];>> polyval(c,1.5)ans =12.3750NMM:InteractiveComputingwithMatlab page44FunctionsforManipulatingPolynomialsFunction Operationsperformedconv product(convolution)oftwopolynomialsdeconv division(deconvolution)oftwopolynomialspoly Createapolynomialhavingspeciedrootspolyder Dierentiateapolynomialpolyval Evaluateapolynomialpolyfit Polynomialcurvetroots FindrootsofapolynomialNMM:InteractiveComputingwithMatlab page45ManipulationofMatricesandVectorsThenameMatlabevolvedasanabbreviationofMATrixLABoratory. ThedatatypesandsyntaxusedbyMatlabmakeiteasytoperformthestandardoperationsoflinearalgebraincludingadditionandsubtraction,multiplicationofvectorsandmatrices,andsolvinglinearsystemsofequations.Chapter7providesadetailedreviewoflinearalgebra. Hereweprovideasimpleintroductiontosomeoperationsthatarenecessaryforroutinecalculation. Vectoradditionandsubtraction Innerandouterproducts Vectorization ArrayoperatorsNMM:InteractiveComputingwithMatlab page46VectorAdditionandSubtractionVectorandadditionandsubtractionareelement-by-elementoperations.Example:>> u = [10 9 8]; (u andv are row vectors)>> v = [1 2 3];>> u+vans =11 11 11>> u-vans =9 7 5NMM:InteractiveComputingwithMatlab page47VectorInnerandOuterProductsTheinnerproductcombinestwovectorstoformascalar=u v=uvT=

uiviTheouterproductcombinestwovectorstoformamatrixA=uTv ai,j=uivjNMM:InteractiveComputingwithMatlab page48InnerandOuterProductsinMatlabInnerandouterproductsaresupportedinMatlabasnaturalextensionsofthemultiplicationoperator>> u = [10 9 8]; (u andv are row vectors)>> v = [1 2 3];>> u*v (inner product)ans =52>> u*v (outer product)ans =10 20 309 18 278 16 24NMM:InteractiveComputingwithMatlab page49Vectorization Vectorizationistheuseofsingle,compactexpressionsthatoperateonallelementsofavectorwithoutexplicitlyexecutingaloop. TheloopisexecutedbytheMatlabkernel,whichismuchmoreecientatloopingthaninterpretedMatlabcode. Vectorizationallowscalculationstobeexpressedsuccintlysothatprogrammersgetahighlevel(asopposedtodetailed)viewoftheoperationsbeingperformed. VectorizationisimportanttomakeMatlaboperateeciently.NMM:InteractiveComputingwithMatlab page50VectorizationofBuilt-inFunctionsMostbuilt-infunctionsupportvectorizedoperations. Iftheinputisascalartheresultisascalar. Iftheinputisavectorormatrix,theoutputisavectorormatrixwiththesamenumberofrowsandcolumnsastheinput.Example:>> x = 0:pi/4:pi (dene a row vector)x =0 0.7854 1.5708 2.3562 3.1416>> y = cos(x) (evaluate cosine of eachx(i)y =1.0000 0.7071 0 -0.7071 -1.0000ContrastwithFortranimplementation:real x(5),y(5)pi = 3.14159624dx = pi/4.0do 10 i=1,5x(i) = (i-1)*dxy(i) = sin(x(i))10 continueNoexplicitloopisnecessaryinMatlab.NMM:InteractiveComputingwithMatlab page51VectorCalculations(3)Moreexamples>> A = pi*[ 1 2; 3 4]A =3.1416 6.28329.4248 12.5664>> S = sin(A)S =0 00 0>> B = A/2B =1.5708 3.14164.7124 6.2832>> T = sin(B)T =1 0-1 0NMM:InteractiveComputingwithMatlab page52ArrayOperatorsArrayoperatorssupportelement-by-elementoperationsthatarenotdenedbytherulesoflinearalgebraArrayoperatorsaredesignatedbyaperiodprependedtothestandardoperatorSymbol Operation.* element-by-elementmultiplication./ element-by-elementrightdivision.\ element-by-elementleftdivision.^ element-by-elementexponentiationArrayoperatorsareaveryimportanttoolforwritingvectorizedcode.NMM:InteractiveComputingwithMatlab page53UsingArrayOperators(1)Examples: Element-by-elementmultiplicationanddivision>> u = [1 2 3];>> v = [4 5 6];>> w = u.*v (element-by-element product)w =4 10 18>> x = u./v (element-by-element division)x =0.2500 0.4000 0.5000>> y = sin(pi*u/2) .* cos(pi*v/2)y =1 0 1>> z = sin(pi*u/2) ./ cos(pi*v/2)Warning: Divide by zero.z =1 NaN 1NMM:InteractiveComputingwithMatlab page54UsingArrayOperators(2)Examples: Applicationtomatrices>> A = [1 2 3 4; 5 6 7 8];>> B = [8 7 6 5; 4 3 2 1];>> A.*Bans =8 14 18 2020 18 14 8>> A*B??? Error using ==> *Inner matrix dimensions must agree.>> A*Bans =60 20164 60>> A.^2ans =1 4 9 1625 36 49 64NMM:InteractiveComputingwithMatlab page55TheMatlabWorkspace(1)Allvariablesdenedastheresultofenteringstatementsinthecommandwindow,existintheMatlabworkspace.AtthebeginningofaMatlabsession,theworkspaceisempty.Beingawareoftheworkspaceallowsyouto Create,assign,anddeletevariables Loaddatafromexternalles ManipulatetheMatlabpathNMM:InteractiveComputingwithMatlab page56TheMatlabWorkspace(2)Theclearcommanddeletesvariablesfromtheworkspace. Thewhocommandliststhenamesofvariablesintheworkspace>> clear (Delete all variables from the workspace)>> who(No response, no variables are dened after clear)>> a = 5; b = 2; c = 1;>> d(1) = sqrt(b^2 - 4*a*c);>> d(2) = -d(1);>> whoYour variables are:a b c dNMM:InteractiveComputingwithMatlab page57TheMatlabWorkspace(3)Thewhoscommandliststhename,size,memoryallocation,andtheclassofeachvariablesdenedintheworkspace.>> whosName Size Bytes Classa 1x1 8 double arrayb 1x1 8 double arrayc 1x1 8 double arrayd 1x2 32 double array (complex)Grand total is 5 elements using 56 bytesBuilt-invariableclassesaredouble,char,sparse,struct,andcell. Theclassofavariabledeterminesthetypeofdatathatcanbestoredinit. Wewillbedealingprimarilywithnumericdata,whichisthedoubleclass,andoccasionallywithstringdata,whichisinthecharclass.NMM:InteractiveComputingwithMatlab page58WorkingwithExternal DataFilesWritedatatoalesave fileNamesave fileName variable1 variable2 . . .save fileName variable1 variable2 . . . -asciiReadindatastoredinmatricesload fileNameload fileName matrixVariableNMM:InteractiveComputingwithMatlab page59LoadingDatafromExternal FileExample: Loaddatafromaleandplotthedata>> load wolfSun.dat;>> xdata = wolfSun(:,1);>> ydata = wolfSun(:,2);>> plot(xdata,ydata)NMM:InteractiveComputingwithMatlab page60TheMatlabPathMatlabwillonlyusethosefunctionsanddatalesthatareinitspath.ToaddN:\IMAUSER\ME352\PS2tothepath,type>> p = path;>> path(p,N:\IMAUSER\ME352\PS2);Matlabversion5hasaninteractivepatheditorthatmakesiteasytoadjustthepathThepathspecicationstringdependsontheoperatingsystem.OnaUnix/Linuxcomputerapathsettingoperationmightlooklike:>> p = path;>> path(p,~/matlab/ME352\ps2);NMM:InteractiveComputingwithMatlab page61Plotting Plotting(x, y)data Axisscalingandannotation 2D(contour)and3D(surface)plottingNMM:InteractiveComputingwithMatlab page62Plotting (x, y)Data(1)TwodimensionalplotsarecreatedwiththeplotfunctionSyntax:plot(x,y)plot(xdata,ydata,symbol)plot(x1,y1,x2,y2, . . . )plot(x1,y1,symbol1,x2,y2,symbol2, . . . )Note: xandymusthavethesameshape,x1andy1musthavethesameshape,x2andy2musthavethesameshape,etc.NMM:InteractiveComputingwithMatlab page63Plotting (x, y)Data(2)Example: Asimplelineplot>> x = linspace(0,2*pi);>> y = sin(x);>> plot(x,y);0 2 4 6 8-1-0.500.51NMM:InteractiveComputingwithMatlab page64LineandSymbol Types(1)Thecurvesforadatasetaredrawnfromcombinationsofthecolor,symbol,andlinetypesinthefollowingtable.Color Symbol Liney yellow . point - solidm magenta o circle : dottedc cyan x x-mark -. dashdotr red + plus -- dashedg green * starb blue s squarew white d diamondk black v triangle(down)^ triangle(up)< triangle(left)> triangle(right)p pentagramh hexagramTochooseacolor/symbol/linestyle,choseoneentryfromeachcolumn.NMM:InteractiveComputingwithMatlab page65LineandSymbol Types(2)Examples:Putyellowcirclesatthedatapoints:plot(x,y,yo)Plotareddashedlinewithnosymbols:plot(x,y,r--)Putblackdiamondsateachdatapointandconnectthediamondswithblackdashedlines:plot(x,y,kd--)NMM:InteractiveComputingwithMatlab page66AlternativeAxisScaling(1)Combinationsoflinearandlogarithmicscalingareobtainedwithfunctionsthat,otherthantheirname,havethesamesyntaxastheplotfunction.Name Axisscalingloglog log10(y)versuslog10(x)plot linearyversusxsemilogx linearyversuslog10(x)semilogy log10(y)versuslinearxNote: Asexpected,useoflogarithmicaxisscalingfordatasetswithnegativeorzerovaluesresultsinaerror.Matlabwillcomplainandthenplotonlythepositive(nonzero)data.NMM:InteractiveComputingwithMatlab page67AlternativeAxisScaling(2)Example:>> x = linspace(0,3);>> y = 10*exp(-2*x);>> plot(x,y);0 1 2 30246810>> semilogy(x,y);0 1 2 310-210-1100101NMM:InteractiveComputingwithMatlab page68Multipleplotspergurewindow(1)Thesubplotfunctionisusedtocreateamatrixofplotsinasinglegurewindow.Syntax:subplot(nrows,ncols,thisPlot)Repeatthevaluesofnrowsandncolsforallplotsinasinglegurewindow. IncrementthisPlotforeachplotExample:>> x = linspace(0,2*pi);>> subplot(2,2,1);>> plot(x,sin(x)); axis([0 2*pi -1.5 1.5]); title(sin(x));>> subplot(2,2,2);>> plot(x,sin(2*x)); axis([0 2*pi -1.5 1.5]); title(sin(2x));>> subplot(2,2,3);>> plot(x,sin(3*x)); axis([0 2*pi -1.5 1.5]); title(sin(3x));>> subplot(2,2,4);>> plot(x,sin(4*x)); axis([0 2*pi -1.5 1.5]); title(sin(4x));(Seenextslidefortheplot.)NMM:InteractiveComputingwithMatlab page69Multipleplotspergurewindow(2)0 2 4 6-1.5-1-0.500.511.5sin(x)0 2 4 6-1.5-1-0.500.511.5sin(2x)0 2 4 6-1.5-1-0.500.511.5sin(3x)0 2 4 6-1.5-1-0.500.511.5sin(4x)NMM:InteractiveComputingwithMatlab page70PlotAnnotationName Operation(s)performedaxis Resetaxislimitsgrid Drawgridlinescorrespondingtothemajormajorticksonthexandyaxesgtext Addtexttoalocationdeterminedbyamouseclicklegend Createalegendtoidentifysymbolsandlinetypeswhenmultiplecurvesaredrawnonthesameplottext Addtexttoaspecied(x, y)locationxlabel Labelthex-axisylabel Labelthey-axistitle AddatitleabovetheplotNMM:InteractiveComputingwithMatlab page71PlotAnnotationExample>> D = load(pdxTemp.dat); m = D(:,1); T = D(:,2:4);>> plot(m,t(:,1),ro,m,T(:,2),k+,m,T(:,3),b-);>> xlabel(Month);>> ylabel(Temperature ({}^\circ F));>> title(Monthly average temperature at PDX);>> axis([1 12 20 100]);>> legend(High,Low,Average,2);2 4 6 8 10 122030405060708090100MonthTemperature ( F)Monthly average temperatures at PDXHigh LowAverageNote: ThepdxTemp.datleisinthedatadirectoryoftheNMMtoolbox. MakesurethetoolboxisinstalledandisincludedintheMatlabpath.NMM:InteractiveComputingwithMatlab page72