matlab lecture 7 – calculus 微积分 ref: symbolic...

Download MATLAB Lecture 7 – Calculus 微积分 Ref: Symbolic …gdjpkc.xmu.edu.cn/FileDown.aspx?dID=193&DownLink=Q... · MATLAB Lecture 7 School of Mathematical Sciences Xiamen University

If you can't read please download the document

Upload: truongdung

Post on 10-Sep-2018

240 views

Category:

Documents


0 download

TRANSCRIPT

  • MATLABLecture 2 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec21

    MATLABLecture2SolvingLinearSystemsofEquations

    Ref:MATLABMathematicsMatricesandLinearAlgebra

    SolvingLinearSystemsofEquationsl Vocabulary:

    coefficientmatrix linearSystemsofEquationsrowelementary transpositions basisbackslash leastsquaressolutionnonsingularmatrix particularsolutionhomogeneoussystem solutionspacelinearhomogeneousequationnonhomogeneoussystemlinearlyindependent pseudoinverserational componentdeterminant rankoverdeterminedsystemunderdeterminedsystemorthonormalbasis null

    l Someoperationsandfunctions . \ rank det inv rref null

    l Applicationonsolvinglinearsystemsofequations Ax=b,Aisanmnmatrix Review: b=0

    Theoryr(A)=n, thereisonlyoneexactsolutionzero.r(A)

  • MATLABLecture 2 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec22

    MATLAB

    NonsingularCoefficientMatrix(canbeverifiedbydetorrankfunctions)

    >> A=pascal(3) %ObtainaPascalmatrix>>u=[314]>>x=A\u %Tryx=pinv(A)*ux=inv(A*A)*A*ux=

    10125

    SingularCoefficientMatrix

    If A is singular, the solution to AX=B either does not exist, or is not unique. The backslashoperator,A\B, issuesawarningifAisnearlysingularandraisesanerrorconditionif itdetectsexactsingularity.

    IfAissingularandAX=bhasasolution,youcanfindaparticularsolutionthatisnotunique,bytyping>>P=pinv(A)*b

    pinv(A)isaMoorePenrosepseudoinverseofA.TheMoorePenrosepseudoinverseisamatrixBofthesamedimensionsasA'satisfyingfourconditions:A*B*A=AB*A*B=BA*BisHermitianB*AisHermitianThecomputationisbasedonsvd(A).

    If AX = b does not have an exact solution, pinv(A) returns a leastsquares solution.priv(A)=(AA)1A

    Forexample,>> A=[1 3 7

    1 4 41 10 18]

    issingular,asyoucanverifybytyping>>det(A)

    ans=0

  • MATLABLecture 2 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec23

    UnderdeterminedSystems

    >>R=fix(10*rand(2,4)) % Obtainanintegermatrixby rand and fixfunctionR=

    6 8 7 33 5 4 1

    >>b=fix(10*rand(2,1))b=

    12

    >>formatrat %displaythesolutioninrationalformat>>x0=R\b %findsabasicsolution,whichhasatmostmnonzerocomponentsx0=

    05/70

    11/7>>Z=null(R,'r') %find anorthonormalbasis() forthenullspaceof RZ=

    1/2 7/61/2 1/21 00 1

    ItcanbeconfirmedthatR*Ziszeroandthatanyvectorxwhere>>symsk1k2k %Definethreesymbolvariables>>k=[k1k2]>>x=x0+Z*k %Generalsolutions

    ColumnFullRank Systems>>x=A\b>>x=pinv(A)*b>>x=inv(A'*A)*A'*btheoreticallycomputesthesameleastsquaressolutionx,althoughthebackslashoperatordoesitfaster.

    Adoesnothavefullrankx=A\b %abasicsolutionithasatmostrnonzerocomponents,whereristherankofA.x=pinv(A)*b %theminimalnormsolutionbecauseitminimizesnorm(x).x=inv(A'*A)*A'*b %failsbecauseA'*Aissingular.

    Example>> A=fix(10*rand(3))>>b=fix(10*rand(3,1))>> ABar=[A b]

  • MATLABLecture 2 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec24

    >>d=rref(ABar) %Thelastcolumnofdisthesolutionofsystem

    d=

    1 0 0 1/80 1 0 73/480 0 1 119/48

    MATLAB Lecture 3 - Linear space.pdf

  • MATLABLecture 3 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec31

    MATLABLecture3LinearSpace

    Ref:MATLABMathematicsMatricesandLinearAlgebra

    SolvingLinearSystemsofEquationsl Vocabulary:

    Vector/linearspace/ linearrelationlinearcombination linearexpression/representationlinearly dependence/correlation linearlydependentlinearly independence linearly independentLinearspace linearspanningdimension linearsubspacemaximallinearlyindependentsubsetscalar spanbasis

    factorization symmetricmatrixproduct triangularmatrixtranspose uppertriangularmatrixlowertriangularmatrix diagonalmatrixpermutation orthogonalmatrixunitarymatrix

    l Someoperationsandfunctionsrank rref rrefmovie null

    l Applicationon linearspace Review:

    Let 1 2, ,..., nx x x bevectorsinvectorspaceV.Asumof theform 1 1 2 2 ... n nk x k x k x + + + ,

    where 1 2, ,..., nk k k arescalars,iscalledalinearcombinationof 1 2, ,..., nx x x .Thesetof

    all linear combinations of 1 2, ,..., nx x x is called the span of 1 2, ,..., nx x x . The span of

    1 2, ,..., nx x x willbedenotedby 1 2Span( , ,..., )nx x x .

    Thevectors 1 2, ,..., nx x x inavectorspace V aresaidtobe linearlyindependentif

    1 1 2 2 ... n nk x k x k x + + +

    impliesthatallthescalars 1 2, ,..., nk k k mustequal0.

  • MATLABLecture 3 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec32

    Iftheonlywaythelinearcombination 1 1 2 2 ... n nk x k x k x + + + canequalthezerovector

    isforallscalars 1 2, ,..., nk k k tobe0,then 1 2, ,..., nx x x arelinearlyindependent.

    The vectors 1 2, ,..., nx x x in a vector spaceV are said to be linearly dependent if there

    existscalars 1 2, ,..., nk k k notallzerosuchthat

    1 1 2 2 ... n nk x k x k x + + + .

    If there are nontrivial choices of scalars for which the linear combination

    1 1 2 2 ... n nk x k x k x + + + equals the zero vector, then 1 2, ,..., nx x x are linearly

    dependent.

    A vector x is said to canbe written as a linear combination of 1 2, ,..., nx x x if there

    existscalars 1 2, ,..., nk k k suchthat 1 1 2 2 ... n nx k x k x k x = + + + .

    Thevectors 1 2, ,..., nx x x inavector spaceVare said tobeabasis ofV if 1 2, ,..., nx x x

    are linearly independent and for any vector Vx can bewritten (uniquely) asa linear

    combinationof 1 2, ,..., nx x x .TheniscalledasthedimensionofV,andwillbedenotedby

    dim(V) .

    LetSdenotesasetofvectors 1 2, ,..., nx x x inavectorspaceV. 1 2, , ..., ri i ix x x isasubsetof

    S.Ifforany Sx , x canbewrittenuniquelyasalinearcombinationof1 2, , ...,

    ri i ix x x ,

    1 2, , ...,

    ri i ix x x willbecalledasoneofthemaximallinearlyindependentsubsetsof S.

    MATLABsupposethat 1V Rn =

    linearrelation

    >> A=fix(10*rand(3,3)) %ObtainasetofvectorswhicharethecolumnsofA>>r=rank(A)>>ifr==3

    disp ThecolumnsofAarelinearlyindependent.else

    disp ThecolumnsofAarelinearlydependent.end

    linearcombination

  • MATLABLecture 3 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec33

    >> A=fix(10*rand(3,2)) %ObtainasetofvectorswhicharethecolumnsofA>>x=fix(10*rand (3,1))>>r0=rank(A)>>r1=rank([Ax])>>ifr0==r1

    disp xcanbewrittenbythecolumnsofA.else

    disp xcannotbewrittenbythecolumnsofA.end

    basisofavectorspace

    >> A=fix(10*rand(3,4)) %ObtainasetofvectorswhicharethecolumnsofA>>B=rref(A) % ObservethecolumnsofBwemayobtainthebasisofthelinear

    spanningspaceofcolumnsofA>>B=rrefmovie (A) %Movieofthecomputationofthereducedrowechelonform

    l *Advancedstudyforlinearsystem Cholesky,LU,andQRFactorizations ()lu qr chol tic toc TheoremAllthreeofthesefactorizationsmakeuseoftriangularmatriceswherealltheelementseitherabove or below the diagonal are zero. Systems of linear equations involving triangularmatricesareeasilyandquicklysolvedusingeitherforwardorbacksubstitution.

    TheCholesky factorizationexpressesasymmetricmatrixastheproductofatriangularmatrixanditstranspose A R R = ,where R isanuppertriangularmatrix.

    LUfactorization,orGaussianelimination,expressesanysquarematrixAastheproductofapermutationofalowertriangularmatrixandanuppertriangularmatrix A LU = whereLisa permutation of a lower triangular matrix with ones on its diagonal and U is an uppertriangularmatrix.

    Theorthogonal,orQR, factorizationexpressesanyrectangularmatrixastheproductofanorthogonalorunitarymatrixandanuppertriangularmatrix.Acolumnpermutationmayalso

    beinvolved. A QR = or AP QR = whereQisorthogonalorunitary,Risuppertriangular,

    andP isapermutation.

    Anorthogonalmatrix,oramatrixwithorthonormalcolumns,isarealmatrixwhosecolumns

    allhaveunitlengthandareperpendiculartoeachother.IfQisorthogonal,then Q Q I = .

    Forcomplexmatrices,thecorrespondingtermisunitary.

  • MATLABLecture 3 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec34

    MATLAB Ax=bCholesky>> A =fix(10*rand(3))>>d =linspace(1,50,3) %Generatesarowvectorof3linearlyequally spacedpoints

    between 1and 50>>Diag_d =diag(d) %Generateadiagonalmatrixwiththe inputarguments>>A= A*Diag_d*(A) %Generateasymmetricmatrix>>b=fix(10*rand(3,1))>>R=chol(A)>>x=R\(R'\b)

    LU>> A =fix(10*rand(3))>>b=fix(10*rand(3,1))>>[L,U]=lu(A)>>x=U\(L\b)

    QR>> A =fix(10*rand(3))>>b=fix(10*rand(3,1))>>[Q,R]= qr(a)>>x=R\(Q\b)

    >> A =fix(10*rand(100))>>d=linspace(1,50,100) %Generatesarowvectorof 100linearly equally spaced

    pointsbetween 1and 50>>Diag_d =diag(d) %Generateadiagonalmatrixwiththe inputarguments>>A= A*Diag_d*(A)>>b=fix(10*rand(100,1))>>ticR=chol(A)x_chol=R\(R\b)t_chol=toc %Computethetimespent>>tic[L,U]=lu(A)x_LU=U\(L\b)t_LU=toc>>tic[Q,R]=qr(A)x_QR=R\(Q\b)t_QR=toc

    MATLAB Lecture 4 - Eigenvalue.pdf

  • MATLABLecture 4 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec41

    MATLABLecture4Eigenvalues

    Ref:MATLABMathematicsMatricesandLinearAlgebra

    SolvingLinearSystemsofEquationsl Vocabulary:

    coefficients characteristicpolynomialroot characteristicrootseigenvalues eigenvectoridentitymatrix decompositiondefectivematrixorthogonalmatrix unitarymatrixnonsymmetric symmetricroundofferror diagonalizeconjugatetranspose associatematrixdefectivematrixnotdiagonalizablesingularvaluedecompositionSchurdecomposition Schur similarmatrixgeometricmultiplicity algebraicmultiplicity

    l Somefunctionseig polv roots schur svd

    l Eigenvalue&*singularvaluedecomposition EigenvaluesAneigenvalueandeigenvectorofasquarematrixAareascalar andanonzerovectorvthatsatisfy

    Av v =EigenvalueDecompositionWith the eigenvalues on the diagonal of a diagonal matrix and the correspondingeigenvectorsformingthecolumnsofamatrixV,wehave

    AV V = If Visnonsingular,thisbecomestheeigenvaluedecomposition

    1A V V =

    Agoodexampleisprovidedbythecoefficientmatrixoftheordinarydifferentialequation>> A=[0 6 1

    6 2 165 20 10]

    >>lambda=eig(A) %producesacolumnvectorcontainingtheeigenvalues.lambda=

  • MATLABLecture 4 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec42

    3.07102.4645+17.6008i2.464517.6008i

    >>[V,D]=eig(A) %computestheeigenvectorsandstorestheeigenvaluesinadiagonalmatrix.

    V=0.8326 0.2003 0.1394i 0.2003+0.1394i0.3553 0.2110 0.6447i 0.2110 +0.6447i0.4248 0.6930 0.6930

    D=3.0710 0 0

    0 2.4645+17.6008i 00 0 2.464517.6008i

    Thefirsteigenvectorisrealandtheothertwovectorsarecomplexconjugatesofeachother.AllthreevectorsarenormalizedtohaveEuclideanlength,norm(v,2),equaltoone.ThematrixV*D*inv(V),whichcanbewrittenmoresuccinctlyasV*D/V,iswithinroundofferrorofA.And,inv(V)*A*V,orV\A*V,iswithinroundofferrorofD.

    DefectiveMatricesSomematricesdonothaveaneigenvectordecomposition.Thesematricesaredefective,ornotdiagonalizable.Forexample,>> A=[6 12 19

    9 20 334 9 15]

    >>[V,D]=eig(A)V=

    0.4741 0.4082 0.40820.8127 0.8165 0.81650.3386 0.4082 0.4082

    D=1.0000 0 0

    0 1.0000 00 0 1.0000

    Thereisadoubleeigenvalueat 1 = .ThesecondandthirdcolumnsofVarethesame.Forthismatrix,afullsetoflinearlyindependenteigenvectorsdoesnotexist.TheoptionalSymbolicMathToolboxextendsthecapabilitiesofMATLABbyconnectingtoMaple, apowerful computeralgebra system.Oneof the functionsprovidedby the toolboxcomputes the Jordan Canonical Form. This is appropriate for matrices like our example,whichis3by3andhasexactlyknown,integerelements.>>[X,J]=jordan(A)X=

    1.7500 1.5000 2.75003.0000 3.0000 3.00001.2500 1.5000 1.2500

  • MATLABLecture 4 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec43

    J=1 0 00 1 10 0 1

    The Jordan Canonical Form is an important theoretical concept, but it is not a reliablecomputationaltoolforlargermatrices,orformatriceswhoseelementsaresubjecttoroundofferrorsandotheruncertainties.

    SchurDecompositioninMATLABMatrixComputationsThe MATLAB advanced matrix computations do not require eigenvalue decompositions.Theyarebased,instead,ontheSchurdecomposition

    'A USU =whereU is anorthogonalmatrixand S is ablock upper triangularmatrixwith1by1and2by2blocks on the diagonal.Theeigenvaluesare revealedby the diagonalelementsandblocksofS,while thecolumnsofU provideabasiswithmuchbetternumericalpropertiesthanasetofeigenvectors.TheSchurdecompositionofourdefectiveexampleis>>[U,S]=schur(A)U=

    0.4741 0.6648 0.57740.8127 0.0782 0.57740.3386 0.7430 0.5774

    S=1.0000 20.7846 44.6948

    0 1.0000 0.60960 0 1.0000

    Thedoubleeigenvalueiscontainedinthelower2by2blockofS.

    *SingularValueDecompositionAsingularvalueandcorrespondingsingularvectorsofarectangularmatrixAareascalar andapairofvectorsuand vthatsatisfy

    , 'Av u A u v = =

    With the singular values on the diagonal of a diagonal matrix and the correspondingsingularvectorsformingthecolumnsoftwoorthogonalmatricesUand V,wehave

    , 'AV U A U V = =

    Since Uand Vareorthogonal,thisbecomesthesingularvaluedecomposition'A U V =

    ThefullsingularvaluedecompositionofanmbynmatrixinvolvesanmbymU,anmbyn ,andan nbynV.Inotherwords,Uand Varebothsquareand isthesamesizeasA.IfA has many more rows than columns, the resultingU can be quite large, but most of itscolumns are multiplied by zeros in . In this situation, the economy sized decompositionsavesbothtimeandstoragebyproducingan mbynU,an nbyn andthesame V.

  • MATLABLecture 4 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec44

    The eigenvalue decomposition is the appropriate tool for analyzing a matrix when itrepresentsamapping fromavector space into itself, as itdoes for an ordinary differentialequation. On the other hand, the singular value decomposition is the appropriate tool foranalyzing a mapping from one vector space into another vector space, possibly with adifferent dimension. Most systems of simultaneous linear equations fall into this secondcategory.

    If A is square, symmetric, and positive definite, then its eigenvalue and singular valuedecompositionsarethesame.But,asAdepartsfromsymmetryandpositivedefiniteness,thedifference between the two decompositions increases. In particular, the singular valuedecomposition of a realmatrix is always real, but the eigenvalue decomposition of a real,nonsymmetricmatrixmightbecomplex.>> A=[9 4

    6 82 7]

    >>[U,S,V]=svd(A) %thefullsingularvaluedecompositionU=

    0.6105 0.7174 0.33550.6646 0.2336 0.70980.4308 0.6563 0.6194

    S=14.9359 0

    0 5.18830 0

    V=0.6925 0.72140.7214 0.6925

    YoucanverifythatU*S*V'isequalto Atowithinroundofferror.

    >>[U,S,V]=svd(A,0) %theeconomysizedecompositionisonlyslightlysmaller.U=

    0.6105 0.71740.6646 0.23360.4308 0.6563

    S=14.9359 0

    0 5.1883V=

    0.6925 0.72140.7214 0.6925

    Again,U*S*V'isequalto Atowithinroundofferror.

    MATLAB>>A=round(10*randn(3))

  • MATLABLecture 4 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec45

    A=

    4 3 1217 11 01 12 3

    >>p_A=poly(A) %computesthecoefficientsofthecharacteristicpolynomialof Aans=1.0e+003*0.0010 0.0120 0.0380 2.0310

    >>r=roots(p_A)r=16.8781

    2.4391+10.6951i2.4391 10.6951i

    Weusuallyuse eig tocomputetheeigenvaluesofamatrixdirectly.

    MATLAB Lecture 5 - Symbol Computation.pdf

  • MATLABLecture5 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec51

    MATLABLecture5SymbolComputation

    Ref: Symbolic Math ToolboxGetting Started

    Symbolic Math ToolboxUsing the Symbolic Math ToolboxTheseversionsof theSymbolicMathToolboxesaredesigned toworkwithMATLAB6orgreaterandMaple8.

    l Vocabulary:datatype toolboxsymbol symbolcomputationsymbolicobject numericalvaluevariable representstore stringexpression equationsubstitute functionabstract indeterminatecirculantmatrix nested/horner collecting expandfactor factoringalgebraic trigonometricidentities transformsimplification

    l Somefunctionssym syms simple simplify collect expand horner factor *findsym*sum *double *eval

    l SymbolicMathToolbox SymbolicObjectsThe SymbolicMath Toolbox defines a newMATLAB data type called a symbolic object.(SeeProgrammingandDataTypesintheonlineMATLABdocumentationforanintroductiontoMATLABclassesandobjects.)Internally,asymbolicobjectisadatastructurethatstoresastring representation of the symbol. TheSymbolicMathToolbox uses symbolic objects torepresent symbolic variables, expressions, andmatrices.Theactualcomputations involvingsymbolic objects are performed primarily byMaple, mathematical software developed byWaterlooMaple,Inc.

    The following example illustrates the difference between a standardMATLAB data type,suchasdouble,andthecorrespondingsymbolicobject.TheMATLABcommand>>sqrt(2) %returnsafloatingpointdecimalnumber:ans=

  • MATLABLecture5 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec52

    1.4142>>a=sqrt(sym(2)) %usingsymbolicnotationforthesquarerootoperationa=2^(1/2)MATLAB gives the result 2^(1/2), which means 21/2, without actually calculating anumerical value. MATLAB records this symbolic expression in the string that represents2^(1/2).You can always obtain the numerical value of a symbolic object with the doublecommand:>>double(a)ans=

    1.4142Noticethattheresultisindented,whichtellsyouithasdatatypedouble.Symbolicresultsarenotindented.

    Whenyoucreateafractioninvolvingsymbolicobjects,MATLABrecordsthenumeratoranddenominator.Forexample:>>sym(2)/sym(5)+sym(1)/sym(3) %performsarithmeticonsymbolicobjectsans=11/15>>2/5+1/3 %givestheanswerasadecimalfractionans=

    0.7333

    TheSymbolicMathToolboxenablesyoutoperformavarietyofsymboliccalculationsthatariseinmathematicsandscience. CreatingSymbolicVariablesandExpressions>>x=sym('x') %constructsymbolicvariable>>a=sym('alpha+2') %constructsymbolicexpression>>rho=sym('(1+sqrt(5))/2') %useasymbolicvariabletorepresentthegoldenratio>>f1=rho^2rho 1f1=(1/2+1/2*5^(1/2))^23/21/2*5^(1/2)>>eval(f1) %evaluatef1ans=

    0

    >>f2=sym('a*x^2+b*x+c') % assignsthesymbolicexpressiontothevariablef2

    Toperformsymbolicmathoperations(e.g.,integration,differentiation,substitution,etc.)onf2,youneedtocreatethevariablesexplicitly.Abetteralternativeistoenterthecommands

    >>a=sym('a')b=sym('b')c=sym('c')x=sym('x')orsimply>>symsabcx

  • MATLABLecture5 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec53

    >>f2=sym('a*x^2+b*x+c')or>>f2=a*x^2+b*x+c

    Ingeneral,youcanusesymorsymstocreatesymbolicvariables.Werecommendyouusesymsbecauseitrequireslesstyping.Ifyouwanttogenerationansymbolicequation, thecodef2=a*x^2+b*x+c=0is illegal.The correctcommandisf2=sym('a*x^2+b*x+c=0')or f2=sym('a*x^2+b*x+c=0').

    Note Tocreateasymbolicexpressionthatisaconstant,youmustusethe symcommand.>>s_5=sym('5')s_5/3 %createasymbolic5ans=5/3>>a_5=5 a_5/3 %createanumber5ans=

    1.6667

    Ifyousetavariableequaltoasymbolicexpression,andthenapplythesymscommandtothevariable,MATLABremovesthepreviouslydefinedexpressionfromthevariable.>>symsab>>f3=a+b %createasymbolicvariablef3,whosevalueisasymbolicexpressiona+bf3=a+b>>symsf3 %removesthepreviouslydefinedexpressionfromthevariable.>>f3f3=f3

    ThesubsCommandYoucansubstituteanumericalvalueforasymbolicvariableusingthe subscommand.to>>f4=2*x^2 3*x+1 %createa char variablef4,equivalenttosymf4

    f4=2*x^23*x+1>>subs(f4,1) %substitutethevaluex=1inf4,i.e.2*1^23*1+1ans=

    0*Note To substitute a matrix A into the symbolic expression f, use the commandpolyvalm(sym2poly(f), A), which replaces all occurrences of x by A, and replaces theconstanttermoffwiththeconstanttimesanidentitymatrix.>> A=[1234]A =

    1 23 4

    >>polyvalm(sym2poly(f4), A)???Function'sym2poly'isnotdefinedforvaluesofclass'char'.

  • MATLABLecture5 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec54

    >>symsf4 %define f4asansymbolicvariable>>f4=sym('2*x^23*x+1') % assignsthesymbolicexpressiontothevariablef4or>>symsxf4=2*x^23*x+1f4=2*x^23*x+1>>polyvalm(sym2poly(f4), A) %computematrixpolynomial2*A^23*A+Ians=

    12 1421 33

    When your expression contains more than one variable, you can specify the variable forwhichyouwanttomakethesubstitution.>>symsxy>>f5=x^2*y+5*x*sqrt(y)>>subs(f5,x,3) %substitutethevaluex=3inthesymbolicexpressionans=9*y+15*y^(1/2)>>subs(f5,y,3) %tosubstitutey=3ans=3*x^2+5*x*3^(1/2)

    CreatingaSymbolicMatrixA circulant matrix has the property that each row is obtained from the previous one bycyclicallypermutingtheentriesonestepforward.Youcan,usingthecommands>>symsabc>> A=[abcbcacab] %createthecirculantmatrixAwhoseelementsarea,b,andcA=[a,b,c][b,c,a][c,a,b]SinceAiscirculant,thesumovereachrowandcolumnisthesame.Tocheckthisforthefirstrowandsecondcolumn,enterthecommand>>sum(A(1,:))ans=a+b+c>>sum(A(1,:))==sum(A(:,2)) %Thisisalogicaltesttocheckwhetherthesumof

    thefirstrow isequaltothatofthesecondrow.ans=

    1Itimpliesthatthesumofthefirstrowisequaltothatofthesecondrow.Iftheansweris0,itmeansthesumofthefirstrowisnotequaltothatofthesecondrow.>>symsalphabeta>> A(2,3)=beta % replacethe(2,3)entryofAwithbeta

  • MATLABLecture5 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec55

    >> A=subs(A,b,alpha) %replace thevariablebwithalphaA=[ a,alpha, c][alpha, c, beta][ c, a,alpha]Fromthisexample,youcanseethatusingsymbolicobjects isverysimilar tousingregularMATLABnumericobjects.

    Simplificationspretty>>clear>>symsx>>f=x^36*x^2+11*x6>>g=(x1)*(x2)*(x3)>>h=6+(11+(6+x)*x)*x>>pretty(f),pretty(g),pretty(h) %generate theirprettyprintedforms3 2x6x +11x6(x1)(x 2)(x 3)6+(11+(6+x)x)x

    collectcollect(f) views f as a polynomial in its symbolic variable, say x, and collects all thecoefficientswiththesamepowerofx.Asecondargumentcanspecifythevariableinwhichtocollecttermsifthereismorethanonecandidate.f collect(f)(x1)*(x2)*(x3) x^36*x^2+11*x6x*(x*(x6)+11)6 x^36*x^2+11*x6(1+x)*t+x*t 2*x*t+t

    expandexpand(f) distributesproductsoversumsandappliesotheridentitiesinvolvingfunctionsofsums.f expand(f)a*(x+y) a*x+a*y(x1)*(x2)*(x3) x^36*x^2+11*x6x*(x*(x6)+11)6 x^36*x^2+11*x6exp(a+b) exp(a)*exp(b)cos(x+y) cos(x)*cos(y)sin(x)*sin(y)cos(3*acos(x)) 4*x^33*x

    hornerhorner(f) transformsasymbolicpolynomialfintoitsHorner,ornested,representation.f horner(f)

  • MATLABLecture5 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec56

    x^36*x^2+11*x6 6+(11+(6+x)*x)*x1.1+2.2*x+3.3*x^2 11/10+(11/5+33/10*x)*x

    factorIffisapolynomialwithrationalcoefficients,thestatementfactor(f) expressesfasaproductofpolynomialsoflowerdegreewithrationalcoefficients.Iffcannotbefactoredovertherationalnumbers,theresultisfitself.f factor(f)x^36*x^2+11*x6 (x1)*(x2)*(x3)x^36*x^2+11*x5 x^36*x^2+11*x5x^6+1 (x^2+1)*(x^4x^2+1)

    Here is anotherexample involving factor. It factorspolynomialsof the formx^n+1.Thiscode>>symsx>>n=(1:9)'>>p=x.^n+1>>f=factor(p)>>[p,f]returns a matrix with the polynomials in its first column and their factored forms in itssecond.[ x+1, x+1][ x^2+1, x^2+1][ x^3+1, (x+1)*(x^2x+1)][ x^4+1, x^4+1][ x^5+1, (x+1)*(x^4x^3+x^2x+1)][ x^6+1, (x^2+1)*(x^4x^2+1)][ x^7+1, (x+1)*(1x+x^2x^3+x^4x^5+x^6)][ x^8+1, x^8+1][ x^9+1, (x+1)*(x^2x+1)*(x^6x^3+1)]

    simplifyThesimplifyfunctionisapowerful,generalpurposetoolthatappliesanumberofalgebraicidentitiesinvolvingsums,integralpowers,squarerootsandotherfractionalpowers,aswellasanumberoffunctionalidentitiesinvolvingtrig functions,exponentialandlogfunctions,Besselfunctions,hypergeometricfunctions,andthegammafunction.f simplify(f)x*(x*(x6)+11)6 x^36*x^2+11*x6(1x^2)/(1x) x+1(1/a^3+6/a^2+12/a+8)^(1/3) ((2*a+1)^3/a^3)^(1/3)symsxypositivelog(x*y) log(x)+log(y)exp(x)*exp(y) exp(x+y)cos(x)^2+sin(x)^2 1

  • MATLABLecture5 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec57

    simpleThesimplefunctionhastheunorthodoxmathematicalgoaloffindingasimplificationofanexpression thathas the fewestnumberof characters.Ofcourse, there is littlemathematicaljustificationforclaimingthatoneexpressionis"simpler"thananotherjustbecauseitsASCIIrepresentationisshorter,butthisoftenprovessatisfactoryinpractice.

    Thesimplefunctionachievesitsgoalbyindependentlyapplyingsimplify,collect,factor,andothersimplificationfunctionstoanexpressionandkeepingtrackofthelengthsoftheresults.Thesimplefunctionthenreturnstheshortestresult.

    simple(f) displayseachtrialsimplificationandthesimplificationfunctionthatproduceditintheMATLABcommandwindow.Thesimplefunctionthenreturnstheshortestresult.>>simple(cos(x)^2+sin(x)^2) %displaysthefollowingalternativesimplificationsin

    theMATLABcommandwindow:simplify:1radsimp:cos(x)^2+sin(x)^2combine(trig):1factor:cos(x)^2+sin(x)^2expand:cos(x)^2+sin(x)^2combine:1convert(exp):(1/2*exp(i*x)+1/2/exp(i*x))^21/4*(exp(i*x)1/exp(i*x))^2convert(sincos):cos(x)^2+sin(x)^2convert(tan):(1tan(1/2*x)^2)^2/(1+tan(1/2*x)^2)^2+4*tan(1/2*x)^2/(1+tan(1/2*x)^2)^2collect(x):cos(x)^2+sin(x)^2andreturnsans=1

    f=simple(f) simplyreturnstheshortestexpressionfound.

    >>f=simple(cos(x)^2+sin(x)^2)f=

  • MATLABLecture5 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec58

    1

    [F,how]=simple(f) returnstheshortestresultinthefirstvariableandthesimplificationmethodusedtoachievetheresultinthesecondvariable.

    >>[f,how]=simple(cos(x)^2+sin(x)^2)f=1how=combine

    The simple function sometimes improves on the result returned by simplify, one of thesimplifications that it tries. Forexample,whenapplied to the examplesgiven for simplify,simplereturnsasimpler(oratleastshorter)resultintwocases.f simplify(f) simple(f)(1/a^3+6/a^2+12/a+8)^(1/3) ((2*a+1)^3/a^3)^(1/3) (2*a+1)/asymsxypositivelog(x*y) log(x)+log(y) log(x*y)

    Insomecases,itisadvantageoustoapplysimpletwicetoobtaintheeffectof twodifferentsimplificationfunctions.>>f=(1/a^3+6/a^2+12/a+8)^(1/3)>>Simple_f=simple(f)Simple_f=(2*a+1)/a>>Simple_Simple_f=simple(Simple_f)Simple_Simple_f=2+1/aor>>Simple_Simple_f =simple(simple(f))Simple_Simple_f=2+1/a

    The simple function is particularly effective on expressions involving trigonometricfunctions.f simple(f)cos(x)^2+sin(x)^2 12*cos(x)^2sin(x)^2 3*cos(x)^21cos(x)^2sin(x)^2 cos(2*x)cos(x)+(sin(x)^2)^(1/2) cos(x)+i*sin(x)cos(x)+i*sin(x) exp(i*x)cos(3*acos(x)) 4*x^33*x

    *ThefindsymCommandTo determine what symbolic variables are present in an expression, use the findsym

  • MATLABLecture5 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec59

    command.>>symsabntxz>>c=1>>ff=x^ngg =sin(a*t+b+c) %giventhesymbolicexpressionsfandg>>findsym(ff) %findthesymbolicvariablesinffans=n,x>>findsym(gg) %findthesymbolicvariablesinggans=a,b,t

    *CreatingAbstractFunctions>>f=sym('f(x)') %createanabstract(i.e.,indeterminate)functionThenfactslikeandcanbemanipulatedbythetoolboxcommands.>>df=(subs(f,'x','x+h')f)/'h' %toconstructthefirstdifferenceratioor>>symsxh>>df=(subs(f,x,x+h)f)/hdf=(f(x+h)f(x))/hThisapplicationofsymisusefulwhencomputingFourier,Laplace,andztransforms.

    MATLAB Lecture 1 - Matrices & Arrays.pdf

  • MATLABLecture 1 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec11

    MATLABLecture1_MatricesandArrays

    MATLAB GettingStarted MatricesandArraysMATLAB GettingStarted Expressions

    MATLAB Mathematics MatricesandLinearAlgebra MatricesinMATLAB

    l Vocabulary:addition substrationmultiplication divisionleftdivision powercomplexconjugatetranspose explicitlist, elemententer/input matrix(pl.matrices)array vectorvariable assignmentstatementexpression datarow columndimension

    l UsingMATLABasaScatchpadOperators Expressionsusefamiliararithmeticoperatorsandprecedencerules.

    >>pi*0.1^2ans=

    0.0314>>area=pi*0.1^2 %theareaofacirclewithradius0.1

    area=

    0.0314

  • MATLABLecture 1 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec12

    >>volume=area*0.5%thevolumeofacylinderwithradius0.1andlength0.5

    volume=

    0.0157>>(12+2*(74))/3^2

    ans=

    2

    >>S=11/2+1/31/4+1/51/6...+1/71/8

    S=

    0.6345>>z1=3+4i

    z1=

    3.0000+4.0000i>>z2=1+2*i>>z3=2*exp(i*pi/6)>>z=z1*z2/z3MATLAB Getting Started Matrices and Arrays Expressions Operators

    l EntermatricesinMATLAB Enteranexplicitlistofelements. Loadmatricesfromexternaldatafiles.

    Generatematricesusingbuiltinfunctions.

    CreatematriceswithyourownfunctionsinMfiles.Array:acollectionofdatavaluesorganizedintorowsandcolumnsVector:anarraywithonlyonedimensionMatrix:anarraywithtwoormoredimensionsSize:specifiedbythenumberofrowsandthenumberofcolumnsinthe

    array,withthenumberofrowsmentionedfirst.

    >>[123456789] %createanarrayswith9elements>>[1,2,34,5,67,8,9] %createa33matrix

    ans=

    123

    456

    789>>[123

    456789]

    ans=

    123

    456

    789

    MATLAB Getting Started Matrices and Arrays Matrices and Magic Square

  • MATLABLecture 1 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec13

    Entering Matrices

    1. InitializingVariablesinMATLABVar =expression

    Assigndatatothevariableinanassignmentstatement(). Inputdataintothevariablefromthekeyboard.

    Readdatafromafile.Someruleson variable: Beginwithaletter Followedbyanycombinationofletters,numbersandtheunderscore(_)character Onlythefirst31charactersaresignificant CasesensitiveGoodprogrammingpractice

    Easytoremember(e.g.name,NAME,Namearedifferent)Useonlylowercaseletter(e.g.nameisthebest)

    >>aa=[123456789] %createanarrayswith9elements>>a=[123456789] %createa33matrix

    a=

    123

    456

    789

    >>b=[1,2,34,5,67,8,9] >>c=[1234]>>d=[a(1,2),7+3]MATLAB Getting Started Matrices and Arrays Expressions Variables

    2. InitializingwithShortcutExpressionsbyColonOperator ( )First:incr :last

    >>a1=1:9%obtainarowvectorcontainingtheintegersfrom1to9

    >>a2=1:2:10>>a3=10:3:0>>a4=pi:0.3:pi>>suba1=a(1:2,3)%obtainamatrixsubA1,whichisapartition

    ofmatrixAwiththefirst2elementsofthe3rdcolumnofA>>suba2=a(1:2,:)>>suba3=a(:,2)>>C=a(:,[2,3,1])%foreachoftherowsofmatrixA,reorder

    theelementsintheorder2,3,1>>D=a(:,end)MATLAB GettingStarted MatricesandArrays MatricesandMagicSquare

    TheColonOperator

  • MATLABLecture 1 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec14

    3. ArrayandMatrixOperations

    Operation MATLABForm CommentsArrayAddition a+b Arrayadditionandmatrixadditionareidentical.ArraySubtraction ab Arraysubtractionandmatrixsubtrationareidentical.ArrayMultiplication

    a.*b Elementbyelement multiplication of a and b. Botharraymustbethesameshape,oroneofthemmustbeascalar.

    MatrixMultiplication

    a*b Matrix multiplication of a and b. The number ofcolumnsinamustequaltothenumberofrowsinb, oroneofthemmustbeascalar..

    Array RightDivision

    a./b Elementbyelement division of a and b: a(i,j)/b(i,j).Both arrays must be the same shape, or one of themmustbeascalar.

    Array LeftDivision

    a.\b Elementbyelement division of a and b:b(i,j)/b(i,j).Both arrays must be the same shape, or one of themmustbeascalar.

    Matrix RightDivision

    a/bMatrixdivisiondefinedby 1ab .

    Matrix LeftDivision

    a\bMatrixdivisiondefinedby 1a b .

    ArrayExponentiation

    a.^a Elementbyelement exponentiation of a and b:

    ( , )( , )b i ja i j .Botharraysmustbethesameshape,orone

    ofthemmustbeascalar.

    4. *InitializingwithBuiltinFunctions

    clock,date

    sin,cos,tan,cot,sec,csc,asin,acos

    x.^a,sqrt,exp,log,log10,log2

    sbs,sign,round,fix,floor,ceil,sum,prod,max,min,mean

    sort,rand,randneye,diag

  • MATLABLecture 1 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec15

    MATLAB Mathematics MatricesandLinearAlgebra MatricesinMATLAB

    5. *InitializingVariableswithKeyboardInputmy_val=input(Enteraninputvalue: )

    >>age=input(Pleaseenteryourage:)Pleaseenteryourage:20>>profession=input(Pleaseenteryourprofession:,s)Pleaseenteryourprofession:teacher

    l Clearing>>clc %ClearingtheCommandWindow.Thisdoesnotclearthe

    workspace,butonlyclearstheview.Afterwards,youstill

    canusetheuparrowkeytorecallpreviousfunctions.>>clear %Removeitemsfromworkspace,freeingupsystemmemory.

    MATLAB Lecture 6 - Polynomial.pdf

  • MATLABLecture6 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec61

    MATLABLecture6Polynomial

    Ref: MATLABMathematicsPolynomials and Interpolationl Vocabulary:

    polynomialroot arithmeticoperationmultiply dividederivative differentiationevaluation partialfractionexpansion convolutionproduct deconvolution quotient remaindermultipleroots direct term transferfunction

    l Somefunctionsconv deconv poly polyder polyval polyvalm roots * residue *polyfit

    l Polynomials RepresentingPolynomialsMATLAB represents polynomials as row vectors containing coefficients ordered bydescendingpowers.

    >>p=[10 25] %represents 3 2 5x x

    p=1 0 2 5

    >>sym_p=poly2sym(p) %representsapolynomialinsymformsym_p =x^32*x5

    CreatePolynomials

    >>p=[10 25] %representsapolynomail 3 2 5x x

    p=1 0 2 5

    >>r =[0,1, 1]poly(r) %generateapolynomial ( 1)( 1)x x x + ,whoserootsare0,1,1

    ans=1 0 1 0

    >>a =[1234]poly(a) %generatethecharacteristicpolynomialsofmatrix

    1 23 4

    ,i.e. 21 2

    5 23 4

    =

  • MATLABLecture6 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec62

    ans=1.0000 5.0000 2.0000

    PolynomialEvaluation>>polyval(p,5) %evaluatesapolynomialataspecifiedvalue,say5.ans=

    110>>subs(sym_p,5) %substitutethesymvariable xinsym_pwith5ans=

    110

    >>X=[245103715]>> Y=polyvalm(p,X) %createasquarematrixXandevaluatethepolynomialpatX

    3 2 5Y X X I =

    Y=377 179 439111 81 136490 253 639

    PolynomialRoots>>r=roots(p) %calculatestherootsofapolynomialpr=

    2.09461.0473+ 1.1359i1.0473 1.1359i

    Polynomial ArithmeticoperationAddition>>p2=[02 13]add_p=p+p2 %calculatessumoftwopolynomialspandp2.

    Here thematrixdimensionsmustagree.add_p=

    1 2 3 2>>p3=poly2sym(p2)add_p_sym=sym_p+p3 %sym_ppulsesp3anddisplaythe

    resultin symform.add_p_sym=x^33*x2+2*x^2>>sym2poly(add_p_sym) %returnsarowvectorcontainingthecoefficients

    ofthesymbolicpolynomialPans=

    1 2 3 2Subtraction (Omit.Itissimilartoaddition)Multiplication (Correspondtotheoperationsconvolution)>>a=[12]b=[20 1]c=conv(a,b)poly2sym(c)

  • MATLABLecture6 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec63

    %compute theproductof 2( 2)(2 1)x x +

    ans=2*x^3+4*x^2x2Division (Correspondtotheoperationsconvolutionanddeconvolution)>>[q,r]=deconv(c,a) %dividingc by aisquotientqandremainderrq=

    2 0 1r=

    0 0 0 0

    PolynomialDerivatives

    >>q=polyder(p) %computesthederivativeofpolynomial 3( 2 5)x x

    q=3 0 2

    >>a=[135]b=[246]c=polyder(a,b) %computesthederivativeofthe

    productoftwopolynomials 2 2[( 3 5)(2 4 6)]x x x x + + + +

    c=8 30 56 38

    >>[q,d]=polyder(a,b) %computesthederivativeofthequotientoftwopolynomials

    2

    2

    ( 3 5) ( )(2 4 6) ( )x x q xx x d x

    + + = + +

    q=2 8 2

    d=4 16 40 48 36

    *PartialFractionExpansionresidue finds the partial fraction expansion of the ratio of two polynomials. This isparticularly useful for applications that represent systems in transfer function form. Forpolynomialsband a,iftherearenomultipleroots,

    1 2

    1 2

    ( ) ...( )

    ns

    n

    rr rb x ka x x p x p x p

    = + + + +

    whererisacolumnvectorofresidues,pisacolumnvectorofpolelocations,andkisarowvectorofdirectterms.

    >>b=[48]a=[168] [r,p,k]=residue(b,a) % 24 8 12 86 8 4 2x

    x x x x

    = + + + + +

    r=128

  • MATLABLecture6 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec64

    p=42

    k=[ ]

    Giventhreeinputarguments(r,p,andk),residueconvertsbacktopolynomialform.

    >>[b2, a2]=residue(r,p,k) % 212 8 4 84 2 6 8

    xx x x x

    + = + + + +

    b2=4 8

    a2=1 6 8

    PolynomialFunctionSummaryFunction Descriptionconv Multiplypolynomials.deconv Dividepolynomials.poly Polynomialwithspecifiedroots.polyder Polynomialderivative.polyval Polynomialevaluation.polyvalm Matrixpolynomialevaluation.roots Findpolynomialroots.residue Partialfractionexpansion(residues).polyfit Polynomialcurvefitting.

    MATLAB Lecture 7 - Calculus.pdf

  • MATLABLecture 7 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec71

    MATLABLecture7Calculus

    Ref: Symbolic Math ToolboxUsing the Symbolic Math Toolbox

    Calculusl Vocabulary:

    calculus functioncomposite/compoundfunction inversefunctionlimit derivativedifferentiation differentialquotient,indefinite integral definite integralTaylorseries TaylorexpansionTaylorformula item/termsummation accumulatesingleton dimensionindex/subscript/suffix theNthorderdifference N

    l Somefunctionscompose finverse limit diff int symsum taylor *gradient *sum *prod

    l CalculusThis section explains how to use the Symbolic Math Toolbox to perform many common

    mathematicaloperations.

    Functioncompositioncompose(f,g)returnsf(g(y))wheref=f(x)andg=g(y).Herexisthesymbolicvariableoff

    asdefinedbyfindsym andyisthesymbolicvariableofgasdefinedbyfindsym.compose (f,g,z) returns f(g(z)) where f = f(x), g = g(y), and x and y are the symbolic

    variablesoffandgasdefinedby findsym.compose(f,g,x,z)returns f(g(z))andmakesx theindependentvariableforf.Thatis, if f=

    cos(x/t),then compose (f,g,x,z)returnscos(g(z)/t)whereascompose (f,g,t,z)returnscos(x/g(z)).compose (f,g,x,y,z) returns f(g(z)) and makes x the independent variable for f and y the

    independent variable for g. For f = cos(x/t) and g = sin(y/u), compose (f,g,x,y,z) returnscos(sin(z/u)/t)whereascompose (f,g,x,u,z)returnscos(sin(y/z)/t).

    Examples:>>symsxyztu>>f=1/(1+x^2)g=sin(y)h=x^tp=exp(y/u)

    >>compose(f,g) % 21

    1 sin y +

    >>compose(f,g,t) % 21

    1 sin t +

  • MATLABLecture 7 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec72

    >>compose(h,g,x,z) %sint z

    >>compose(h,g,t,z) % sin zx

    >>compose(h,p,x,y,z) % ( )/ tz ue

    >>compose(h,p,t,u,z) %/y zex

    NOTICE:theorderofthecodesisimportant.>>clearsymsxyzz=exp(y)y=sin(x)compose(z,y),zans=exp(sin(x))z=exp(y)>>clearsymsxyzy=sin(x)z=exp(y)compose(z,y),z %NOTRECOMMENDans=exp(sin(sin(x)))z=exp(exp(x))>>clearsymsuvyzy=sin(u)z=exp(v)compose(z,y) %RECOMMENDtouse

    differentvariablesasindependentvariablefordifferentfunctions

    Functionalinverseg=finverse(f)returnsthefunctionalinverseoff.fisascalarsymrepresentingafunctionof

    exactlyonesymbolicvariable,say'x'.Thengisascalarsym thatsatisfiesg(f(x))=x.g=finverse(f,v)usesthesymbolicvariablev,wherevisasym,astheindependentvariable.

    Then g is a scalar sym that satisfies g(f(v)) = v.Use this formwhen f containsmore than onesymbolicvariable.

    Examples:>>finverse(1/tan(x)) %returnsatan(1/x).>>f=x^2+y>>finverse(f,y) %returnsx^2+y.>>finverse(f)Warning:finverse(x^2+y)isnotunique.>Insym.finverseat43ans=(y+x)^(1/2)

    Limitofanexpressionlimit(F,x,a)takesthe limitofthesymbolicexpressionFasx a.limit(F,a)usesfindsym(F)astheindependentvariable.limit(F)usesa=0asthelimitpoint.limit(F,x,a,'right')orlimit(F,x,a,'left')specifythedirectionofaonesidedlimit.

  • MATLABLecture 7 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec73

    Examples:>>symsxath

    >>limit(sin(x)/x) %evaluate0

    sinlimx

    xx

    ans=1

    >>limit((x2)/(x^24),2) %evaluate 222lim4x

    xx

    ans=1/4

    >>limit((1+2*t/x)^(3*x),x,inf) %evaluate32lim 1x

    x

    tx

    +

    ans=exp(6*t)

    >>limit(1/x,x,0,'right') %evaluate0

    1limx x +

    ans=Inf

    >>limit(1/x,x,0,'left') %evaluate0

    1limx x

    ans=Inf

    >>limit((sin(x+h)sin(x))/h,h,0) %evaluate0

    sin( ) sinlimh

    x h xh

    +

    ans=cos(x)>>v=[(1+a/x)^x,exp(x)]

    >>limit(v,x,inf,'left') %evaluate lim 1 , limx

    x

    x x

    a ex

    +

    ans=[exp(a), 0]

    Differenceandapproximatederivativediff (X),foravectorX,is[X(2)X(1) X(3)X(2) ... X(n)X(n1)].diff (X),foramatrixX,isthematrixofrowdifferences,[X(2:n,:)X(1:n1,:)].diff(X,N)is theNthorderdifferencealongthefirstnonsingletondimension(denoteitby

    dim). If N >= size(X,dim), diff takes successive differences along the next nonsingletondimension.

    diff(X,N,DIM)is theNthdifferencefunctionalongdimensionDIM.IfN>=size(X,DIM),diff returnsanemptyarray.

  • MATLABLecture 7 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec74

    Examples:>>h=.001x=0:h:pi

    >>diff(sin(x.^2))/h %2 2sin( ) sin( ) , : :i i h i h h pih

    = ,thereare approximation

    to2*cos(x.^2).*x,x=0:h:pi

    >>diff((1:10).^2) %evaluate 2 2( 1) , 1, 2,...,10i i i + =

    ans=3 5 7 9 11 13 15 17 19

    >>X=[375257]diff(X) %thesameasdiff(X,1,1)ans=

    1 2 2>>diff(X,1,2)ans=

    4 23 2

    >>diff(X,2,2) %the2ndorderdifferencealongthedimension2ans=

    61

    >>diff(X,3,2)ans=

    Emptymatrix:2by0>>symsxyy=atan((x+1)/(x1))>>yx=diff(y,x)yx=(1/(x1)(x+1)/(x1)^2)/(1+(x+1)^2/(x1)^2)>>yxx=diff(y,x,2)yxx=(2/(x1)^2+2*(x+1)/(x1)^3)/(1+(x+1)^2/(x1)^2)(1/(x1)(x+1)/(x1)^2)/(1+(x+1)^2/(x1)^2)^2*(2*(x+1)/(x1)^22*(x+1)^2/(x1)^3)>>symsxy>>z=x^4+y^4cos(2*x+3*y)

    >>zx=diff(z,x) %compute4 4( cos(2 3 ))x y x y

    x + +

    zx=4*x^3+2*sin(2*x+3*y)

    >>zy=diff(z,y) %computezy

    zy=4*y^3+3*sin(2*x+3*y)

  • MATLABLecture 7 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec75

    >>zxx=diff(zx,x) %compute2

    2

    zx

    ,equivalentto zxx=diff(z,x,2)

    zxx=12*x^2+4*cos(2*x+3*y)

    Integrateint(S) is the indefinite integral of S with respect to its symbolic variable as defined by

    findsym.Sisasym (matrixorscalar).IfSisaconstant,theintegraliswithrespectto'x'.int(S,v)istheindefiniteintegralofSwithrespecttov.visascalarsym.int(S,a,b)isthedefiniteintegralofSwithrespecttoitssymbolicvariablefromatob.aandb

    areeach doubleorsymbolicscalars.int(S,v,a,b)isthedefiniteintegralofSwithrespecttovfromatob.

    Examples:>>symsxx1alphaut>> A=[cos(x*t),sin(x*t)sin(x*t),cos(x*t)]

    >>int(1/(1+x^2)) %compute 21

    1dx

    x + withoutconstantitemCans=atan(x)

    >>int(sin(alpha*u),alpha) %compute sin( )u d withoutconstantitemCans=1/u*cos(alpha*u)

    >>int(x1*log(1+x1),0,1) %compute1

    1 1 10ln(1 )x x dx +

    ans=1/4>>int(4*x*t,x,2,sin(t))ans=2*t*(sin(t)^24)

    >>int([exp(t),exp(alpha*t)]) %compute [ , ]t te dt e dt ans=[ exp(t),1/alpha*exp(alpha*t)]

    >>int(A,t) %compute [ cos , sin sin , cos ]xtdt xtdt xtdt xtdt ans=[1/x*sin(x*t), cos(x*t)/x][ cos(x*t)/x,1/x*sin(x*t)]

    Taylorseriesexpansiontaylor(f)isthefifthorderMaclaurinpolynomialapproximationtof.

  • MATLABLecture 7 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec76

    Threeadditionalparameterscanbespecified,inalmostanyorder.taylor(f,n)isthe(n1)storderMaclaurinpolynomial.taylor(f,a)istheTaylorpolynomialapproximationaboutpointa.taylor(f,x)usestheindependentvariablexinsteadof findsym(f).

    Examples:>>taylor(exp(x)) %evaluatethefirst5itemsof Taylorseriesexpansion at0ans=1x+1/2*x^21/6*x^3+1/24*x^41/120*x^5>>taylor(log(x),6,1) %evaluatethefirst61itemsof Taylorseriesexpansion at1ans=1x+1/2*x^21/6*x^3+1/24*x^41/120*x^5>>taylor(sin(x),6,pi/2) %evaluatethefirst61itemsof Taylorseriesexpansion atpi/2ans=11/2*(x1/2*pi)^2+1/24*(x1/2*pi)^4>>taylor(sin(x)*t,t) %evaluatethefirst5itemsof Taylorseriesexpansion responding

    totans=sin(x)*t>>taylor(sin(x)*t,x) %evaluatethefirst5itemsof Taylorseriesexpansion responding

    to x

    ans=x*t1/6*t*x^3+1/120*t*x^5

    SumofelementsS=sum(X)isthesumoftheelementsofthevectorX.If Xisamatrix,Sisarowvectorwiththesumovereachcolumn.IfXisfloatingpoint,thatisdoubleorsingle,Sisaccumulatednatively,thatisin thesame

    classasX, andShasthesameclassasX.IfXisnotfloatingpoint,SisaccumulatedindoubleandShasclassdouble.S=sum(X,DIM)sumsalongthedimensionDIM.

    Examples:>>X=[012345]>>sum(X) %evaluatearowvectorwiththesumovereachcolumnans=

    3 5 7>>sum(X,1) %evaluatearowvectorwiththesumovereachcolumnans=

    3 5 7>>sum(X,2) %evaluateacolumnvectorwiththesumovereachrowans=

    3

  • MATLABLecture 7 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec77

    12

    Symbolicsummationsymsum(S)istheindefinitesummationofSwithrespecttothesymbolicvariabledetermined

    by findsym.symsum(S,v)istheindefinitesummationwithrespecttov.symsum(S,a,b)and symsum(S,v,a,b)arethedefinitesummationfromatob.

    Examples:>>symskn

    >>a1=simple(symsum(k)) %evaluate1

    0

    k

    ii

    = a1=1/2*k*(k1)

    >>a2=simple(symsum(k,0,n1)) %evaluate1

    0

    n

    kk

    = a2=1/2*n*(n1)

    >>a3=simple(symsum(k,0,n)) %evaluate0

    n

    kk

    = a3=1/2*n*(n+1)

    >>a4=simple(symsum(k^2,0,n)) %evaluate 20

    n

    kk

    = a4=1/6*n*(n+1)*(2*n+1)

    >>symsum(k^2,0,10) %evaluate10 2

    0kk

    = ans=385

    >>symsum(k^2,11,10) %evaluate10 2

    11kk

    = ans=0

    >>symsum(1/k^2) %evaluate 211k

    i i = ans=Psi(1,k)

    >>symsum(1/k^2,1,Inf) %evaluate 211

    k k

    = ans=1/6*pi^2

    MATLAB Lecture 8 - Graphics-Curve.pdf

  • MATLABLecture 8 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec81

    MATLABLecture8GraphicsCurve

    Ref: MATLABGraphicsBasic Plotting Commandsl Vocabulary:

    plot xaxisxdisplay annotatecurve/curvedline explicitimplicit parameterpolarcoordinates boldfacegrid titlefigure legendradian radius

    l Somefunctionsplot ezplot polar plot3 title xlabel ylabel *figure *legend *subplot*gridon *gridoff

    l GraphicsMATLABprovidesavarietyoffunctionsfordisplayingvectordataaslineplots,aswellas

    functionsforannotatingandprintingthesegraphs. Therepresentationofcurveandsurface TherepresentationofcurveonplaneExplicitscheme:y=f(x)Implicitformula:F(x,y)=0

    Parameterrepresentation:( )( )

    x x ty y t

    = =

    Polarcoordinatesrepresentation: ( )f =

    Tabulation,saytableof trigonometric function,experimentaldataetc.Figure,saysinecurve,experimentalcurveetc. TherepresentationofcurveinspaceExplicitscheme:z=f(x,y)Implicitformula:F(x,y,z)=0

    Parameterrepresentation:

    ( , )( , )( , )

    x x u vy y u vz z u v

    = = =

    Dataform, { }, { }, { }, 1, 2,..., , 1, 2,...,i j ijx x y y z z i m j n = = = = = .

    Graphics

  • MATLABLecture 8 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec82

    BasicPlottingCommands PlottingStepsThe process of constructing a basic graph to meet your presentation graphicsrequirementsisoutlinedinthefollowingtable.Thetableshowsseventypicalstepsandsomeexamplecodeforeach.Ifyouareperforminganalysisonly,youmaywanttoviewvariousgraphsjusttoexploreyour data. In this case, steps 1 and 3 may be all you need. If you are creatingpresentation graphics, youmaywant to finetune your graph by positioning it on thepage, setting line styles and colors, adding annotations, and making other suchimprovements.Step TypicalCode1.Prepareyourdata x=0:0.2:12

    y1=bessel(1,x)y2=bessel(2,x)y3=bessel(3,x)

    2.Selectawindowandpositionaplotregionwithinthewindow

    figure(1)subplot(2,2,1)

    3.Callelementaryplottingfunction h=plot(x,y1,x,y2,x,y3)4.Selectlineandmarkercharacteristics

    set(h,'LineWidth',2,{'LineStyle'},{''':''.'})set(h,{'Color'},{'r''g''b'})

    5.Setaxislimits,tickmarks,andgridlines

    axis([0120.51])gridon

    6. Annotate the graph with axislabels,legend,andtext

    xlabel('Time')ylabel('Amplitude')legend(h,'First','Second','Third')title('BesselFunctions')[y,ix]=min(y1)text(x(ix),y,'FirstMin \rightarrow',...'HorizontalAlignment','right')

    7.Exportgraph printdepsc tiff r200myplot

    Plotfunctionplot(X,Y):plotsvector Y versusvectorX.IfXorYisamatrix,thenthevectorisplottedversustherowsorcolumnsofthematrix,whicheverlineup.It can be used to plot of a curve expressed in explicit scheme or parameterrepresentation.

    >>x=[123456]y=[11.52317]>>plot(x,y)

  • MATLABLecture 8 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec83

    >>a=[1:6149162536]>>plot(a)

    Plot sin xover [0, 2 ] withtitleandgrid.

    >>t=0:pi/100:2*pi>>y=sin(t)>>plot(t,y)>>title(Plotofsinxvsx) %titled Plotofsinxvsx>>xlabel(x)ylabel(sinx) %addstextbesidetheXaxis&Yaxis

    onthecurrentaxis>>gridon

  • MATLABLecture 8 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec84

    Plot the curve with sin , cosx a mt y a nt = = over [0, 2 ]t while a=8, m=2 and

    n=5.>>t=linspace(0,2*pi) %generatesarowvectorof100linearlyequallyspaced

    pointsbetween 0and 2.>>a=8>>m=2>>n=5>>x=a*sin(m*t)>>y=a*cos(n*t)>>plot(x,y,b) %colorblue,linestyle

  • MATLABLecture 8 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec85

    PolarPlotspolar(THETA, RHO) makes a plot using polar coordinates of the angle THETA, inradians,versustheradiusRHO.>>g=0.5>>theta=linspace(0,2*pi,51) %generates51linearlyequallyspacedpoints

    between0and2.>>gain=2*g*(1+cos(theta))>>polar(theta,gain,r) %colorred,linestylesolid>>title(\bf Gainversusangle \theta) %boldface,\thetawillbedisplayas

    EzplotFunction EasytousefunctionplotterItisusuallyusedtoplotacurveexpressedinimplicitformula.ezplot(FUN)plotsthefunctionFUN(X)overthedefaultdomain 2*pi

  • MATLABLecture 8 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec86

    Plotthefunction 4 4 4x y a + = over[2,2],wherea=2.

    >>symsxya=2>>f=x^4+y^4a^4>>ezplot(f,[2,2])

    Plot3FunctionPlotlinesandpointsin3Dspace.plot3(x,y,z),wherex,yandzarethreevectorsofthesamelength,plotsalinein3spacethroughthepointswhosecoordinatesaretheelementsofx,yandz.plot3(X,Y,Z),whereX,YandZarethreematricesofthesamesize,plotsseverallinesobtainedfromthecolumnsofX,YandZ.Variouslinetypes,plotsymbolsandcolorsmaybeobtainedwithplot3(X,Y,Z,s)wheres is a 1, 2 or 3 character string made from the characters listed under the plot3command.>>t=0:pi/50:10*pi>>plot3(sin(t),cos(t),t)

  • MATLABLecture 8 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec87

    >>t=0:pi/30:9*pia=20c=3>>x=a*t.*sin(t)y=a*t.*cos(t)z=c*t>>plot3(x,y,z,mo) %colormagenta,linetype circle

    PlottingMultiplePlotsontheSameAxes>>x= pi:pi/20:pi>>y1=sin(x)>>y2=cos(x)>>plot(x,y1,b ) %bluecolorsolid()linestyle>>holdon %afterthiscommand,alladditionalplotswillbelaidontopofthe..

    previouslyexistingplots.>>plot(x,y2,k) %black colordashed()linestyle>>holdoff %switchesplottingbehaviorbacktothedefaultsituation,inwhich

    A newplotreplacesthepreviousone>>legend(sinx,cosx)Or>>x= pi:pi/20:pi>>y1=sin(x)>>y2=cos(x)>>plot(x,y1,b,x,y2,k)>>legend(sinx,cosx)

  • MATLABLecture 8 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec88

    CreateMultipleFigures>>figure(1) %figurewindow1>>x=0:0.05:2>>y1=exp(x) >>plot(x,y1)>>figure(2) %createanotherfigurewindow2>>y2=exp(x)>>plot(x,y2)

    Subplots>>subplot(2,1,1) %create21subplotsincurrentfigure,arrangedin2rows

    and1column,andselectssubplot1toreceiveallcurrentplottingcommands

    >>x= pi:pi/20:pi

  • MATLABLecture 8 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec89

    >>y=sin(x)>>plot(x,y)>>title(1)>>subplot(2,1,2) %create21subplotsincurrentfigure,arrangedin2rows

    and1column,andselectssubplot2toreceiveallcurrentplottingcommands

    >>x= pi:pi/20:pi>>y=cos(x)>>plot(x,y)>>title(2)

    Someexamples>>clearx=pi:pi/10:piy=tan(sin(x))>>y1=sin(tan(x))>>plot(x,y,'rs','linewidth',2,'markeredgecolor','k','markerfacecolor','g','markersize',10)>>holdon>>plot(x,y1,'ko','markeredgecolor','k','markerfacecolor','r','markersize',10)

  • MATLABLecture 8 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec810

    Acurvefittingexample()>>High_boy=[1.55,1.58,1.6,1.64,1.66,1.68,1.7,1.73, 1.78,1.8,1.82,1.85]>>Weight_boy=[60,57,57,65,63, 64,70,65,68,76, 72, 78]>>plot(High_boy,Weight_boy,'b*')>>holdon>>Everage_boy=polyfit(High_boy,Weight_boy,1)>>x=1.5:0.1:1.9boy_line=Everage_boy(1)* x+Everage_boy(2)>>plot(x,boy_line,'g','linewidth',1.2)

    AppendixVariouslinetypes,plotsymbolsandcolorsmaybeobtainedwithPLOT(X,Y,S)whereSisacharacterstringmadefromoneelementfromanyorallthefollowing3columns:

    b blue . point solidg green o circle : dottedr red x xmark . dashdotc cyan + plus dashedm magenta * star (none) no liney yellow s squarek black d diamondv triangle(down)^ triangle(up) triangle(right)p pentagramh hexagram

    You can use a subset of TeX commands embedded in the string to produce special

  • MATLABLecture 8 SchoolofMathematicalSciencesXiamenUniversity http://gdjpkc.xmu.edu.cn

    Lec811

    characters such asGreek letters and mathematical symbols. The following table liststhesecharactersand thecharactersequencesusedtodefine them.