Matlab Tutorial, CDS110-101

Transcription

OutlineIntroductionVariablesOperations and functionsGraphicsProgrammingSimulinkMatlab Tutorial, CDS110-101Elisa Franco29 September 2006Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and riablesArraysBuilt-in variablesOperations and functionsOperationsLinear pts and data managementFunctionsSimulinkElisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and functionsGraphicsProgrammingSimulinkWhat is Matlab?Matlab (stands for ”Matrix laboratory”) is an environment which issuited to work with arrays and matrices, integrating visualizationand computation. Visit the website http://www.mathworks.com.Several toolboxes (i.e. sets of precompiled routines) are available,specifically suited for different engineering fields: statistics, signalprocessing, control, data acquisition, symbiology .Matlab can be used both from the command window and bycoding scripts. GUI’s are available for specific tasks.Files created in Matlab end in .m, data can be saved in files thatend in .mat (we will see how).FrancoMatlab Tutorial,CDS110-101Help: command window Elisa(seenext slide),i.e. help subj or full

OutlineIntroductionVariablesOperations and functionsGraphicsProgrammingSimulinkWhere to get MatlabIMatlab is available for download if you are registered CaltechstudentsIgo to the url http://software.caltech.edu/Ilog in with your CIT (IMSS) email account and pswIgo to the ”software” section and download the latest availableversion of Matlab, R2006b (PC or MAC).IFor MAC users: you need formacosx.htmlElisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and functionsGraphicsProgrammingSimulinkCommand windowElisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and functionsGraphicsProgrammingSimulinkArraysBuilt-in variablesHow to define variablesIn Matlab, variables are arrays. You do not need to define theirformat (int, real .) or dimensions in advance, nor to declare themat the beginning of your program. One is mostly interested indefining:IVectorsIPolynomialsIMatricesElisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and functionsGraphicsProgrammingSimulinkArraysBuilt-in variablesHow to define a vectorTyping: a [1 2 3 4]; or a [ 1, 2, 3, 4]; defines arow vector a ( 1 2 3 4 ). 1 2 Typing: a [1 ; 2 ; 3 ; 4]; defines a column vector a 3 .4You can also use the transpose operation: a [1 ; 2 ; 3 ; 4]0 ;defines again a row vector.Type t [0 : .1 : 1] or t 0 : .1 : 1. Defines a row vectort whose elements range from 0 to 1 and are spaced by .1.To get rid of a, write clear a. (Clear all - clears all vars)Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and functionsGraphicsProgrammingSimulinkArraysBuilt-in variablesComma and semicolonComma: array row separator. Semicolon: column separator.If you do not type a semicolon after defining each variable, you’llhave some hassle, especially if you defined big arrays .Note: Matlab has a built in variable ans that stores the mostrecent variable you defined.Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and functionsGraphicsProgrammingSimulinkArraysBuilt-in variablesHow to define a polynomialTyping: p [ 1 1 3 ];defines a row vector p ( 1 1 3 ), which the environment canalso interpret as a second order polynomial p(s) s 2 s 3.Typing: p [ 1 0 3 1 ];will define a third order polynomial p(s) s 3 3s 1.Matlab offers several functions to solve operations withpolynomials.Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and functionsGraphicsProgrammingSimulinkArraysBuilt-in variablesHow to define a matrixA matrix is a stack of row vectors. Just typeA [ 1 2 3; 1 2 3 ] and you will generate a 2 3 matrix: 1 2 3A 1 2 3To access the (i, j) element of A, just type A(i, j). For instance A(2, 3) will return ans 3. Elements of a matrix can alsobe reassigned, e.g. A(2, 3) 100; will transform A into: 1 2 3A 1 2 100Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and functionsGraphicsProgrammingSimulinkArraysBuilt-in variablesHow to define a matrix 1 2I Transpose: type A A0 : A 2 2 3 3I eye(3): 3 3 identity matrix. eye(4, 5): 4 4identity plus a column of zeros;I zeros(3, 2): 3 2 matrix padded with zeros;I ones(3, 2): 3 2 matrix of ones;I rand(n, m) and randn(n, m): uniformly and normallydistributed n m matrices; 1 0I diag ([1, 2]): diagonal matrix: A 0 2Type help gallery for a list of matrices that can be defined byspecifying their relevant parameters.Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and functionsGraphicsProgrammingSimulinkArraysBuilt-in variablesHow to manage matricesI[ n, m ] size(A) returns the row and cols. number of A. Usesize(A, 2) to access the cols. number.I[ Y , I ] max(A) returns: Y max el. in each row of A; I ,indices of the corresponding element. max(max(A)) returnsthe max el. of A. For vectors, max(v ) returns max el.I[ Y , I ] min(A), see above.IY sort(M) sorts the cols of M in ascending order. See help sort or doc sort for more info.Ifind(M 1) returns the linear indices of els. 1.Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and functionsGraphicsProgrammingSimulinkArraysBuilt-in variablesBuilt-in variablesThere are seven built-in variables (which can be overwritten):Ians, which we have seen already.Ieps is the floating point machine accuracy.Ii and j represent the imaginary unit. You can define complexvariables ( array, polynomial coefficients, matrices), e.g. x 5 j 3 is a complex number.IInf is ”infinity”. 1/0, 22000 and exp(1000) all produce Inf ;log (0) produces Inf .Ipi is π.INaN is ”Not a Number”; this is generated when operationshave undefined numerical results, such as 0/0 or Inf /Inf .Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and ar algebraPolynomialsFunctionsOperations and functionsA complete categorical list of operations and functions available inMatlab cal be found through the Help Contents.A wide number of elementary mathematical functions is offered(exp, sin, log .), together with linear algebra, polynomial tools,specialized math and other categories.Individual toolboxes will offer dedicated routines (e.g. functionminimization routines, Optimization Toolbox; controllability,observability checks, Control Toolbox.).Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and ar algebraPolynomialsFunctionsElementary operationsTwo types of arithmetic operations:I matrix arithmetic operations: rules of linear algebraI array arithmetic operations: carried out element by element.The period character (.) distinguishes the array operations fromthe matrix operations. Examples:I A, B matrices of the same size; A B, A B, A B are thesum, subtraction and matrix multiplication as classicallydefined. A. B is an element-by-element product (A and Bmust have the same size, unless one is a scalar).I Ap is the matrix power. Equivalent to A A . A forp-times. A.p is the array power: equivalent to A(i, j)pelementwise. If p is a matrix, must be of the same size of A.Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and ar algebraPolynomialsFunctionsElementary vector operations table (from Matlab help)Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and ar algebraPolynomialsFunctionsElementary matrix operations table (from Matlab help)I A / B slash or rightdivision; is equivalent toB inv (A).I A \ B backslash orleft division; equivalent toinv (A) B.NOTE: if A is n m,n 6 m and B is m 1,A \ B will compute theleast squares or minimumnorm solution x̄ ofA x B.Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and ar algebraPolynomialsFunctionsRelational operators (Table from Matlab Help)A R B operates elementwise.Returns array where elementsare 1 if R true, 0 if false. Aand B not need to have samesize.Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and ar algebraPolynomialsFunctionsLogic operators (Table from Matlab Help)Again operate elementwise formatrices.To compare expressions:exp1exp1&&exp2 exp2where exp1 and exp2 givescalar logical results.Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and ar algebraPolynomialsFunctionsLinear algebraGiven a square matrix 1M IIIII47258369 determinant: det(M) gives ans 0;rank: rank(M), gives in fact ans 2;null space: null(M) is [0.4082 0.8165 0.4082] ;trace: trace(M) gives ans 15;norm: norm(M, p) gives the p-norm. Ex. norm(M, 1)gives ans 18, while norm(M, 2) gives ans 16.8481. Check help norm for more info .Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and ar algebraPolynomialsFunctionsLinear algebra.continuedIinverse: inv (M). oops we obviously get a Warning:Matrix is close to singular or badly scaled. Results may beinaccurate. RCOND 2.202823e-18. But if the matrix isinvertible, this won’t happen!Ieigenvalues and eigenvectors: [v , e] eig (M) gives 0.2320 0.7858 0.4082 16.116800 1.1168v 0.5253 0.0868 0.8165 , e 0.8187I0.61230.40820000 0.0000singular value decomposition: [U, S, V ] svd(M).Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and ar algebraPolynomialsFunctionsBasic polynomial operationsDefine a polynomial p [ 1 1 1 1 1 ], and q [ 1i.e. p(s) s 4 s 3 s 2 s 1, and q(s) s 2 2.IIII02 ],roots of p: roots(p), gives s1,2 0.3090 0.9511i ands3,4 0.8090 0.5878i.convolution of p and q: conv (p, q) gives ans 1 1 3 3 3 2 2. Also deconv exists.derivative of p: polyder (p) is 4s 3 3s 2 2s 1. Can alsodo polyder (p, q), will find the derivative of the convolution.characteristic polynomial: given our previous matrix M, poly (M)returns ans 1.0000 15.0000 18.0000 0.0000.Obviously one root is zero.Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and ar algebraPolynomialsFunctionsUseful mathematical functionsDefine an array t [0 : .1 : 10]. You can evaluate:Itrigonometric functions:cos(t), sin(t), tan(t), sec(t), tanh(t).Iexponential and logarithm: exp(t), log (t), log 2(t), log10(t).Other useful stuff:Icomplex numbers: real(s), imag (s), abs(s), angle(s).Irounding and remainders: floor (s), ceil(s), mod(s1, s2),rem(s1, s2).Idiscrete math: perm(s), factors(s), factorial(s).Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and functionsGraphicsProgrammingSimulinkSimple graphicsWant to draw your sin(t)? t [0 : .1 : 10]; plot(t, sin(t)) xlabel(0 Time0 ) ylabel(0 sin(t)0 ) title(0 My first plot0 )For more info: helpplot.Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and e: x [ 2 : .1 : 2]; y [ 2 : .1 : 2]; [X , Y ] meshgrid(x, y ); Z X . 2 Y . 2; mesh(X , Y , Z ) xlabel(0 X0 ) ylabel(0 Y0 ) zlabel(0 Z0 ) title(0 My first surface0 )Try also surf (X , Y , Z )! Formore info, type help mesh or help surf .Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and functionsGraphicsProgrammingSimulinkScripts and data managementFunctionsCreate a scriptGo to File NewM-file.This will launch theMatlab editor.Then you can writesome code and debug.Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and functionsGraphicsProgrammingSimulinkScripts and data managementFunctionsControl flowIfor:forIvar exprstatif–else:ifendIexpr1 Tstatelse ifwhile:whileexpr2 Tstatelsestatexpr TstatendendendElisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and functionsGraphicsProgrammingSimulinkScripts and data managementFunctionsExampleNote: comments are preceded by %Figures can be split in more windows.Try to play with the parameters ofthe main equation!Tip: use the smart indent formattingcommand (Edit Select All, Text Smart Indent)!Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and functionsGraphicsProgrammingSimulinkScripts and data managementFunctionsWhere are my data?All your data are stored in theMatlab workspace.Also your commands are stored inthe command history, which can bescrolled up/down.Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and functionsGraphicsProgrammingSimulinkScripts and data managementFunctionsData managementSave the data youproduce:Ito a text fileIin .mat format;more convenient ifneed to utilize themagain in Matlab.Use load mydataElisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and functionsGraphicsProgrammingSimulinkScripts and data managementFunctionsFunctionsIf you need to repeat similar operations,consider defining a function. Example:discretized equations for an oscillator.Important: you need to save the file withthe function name!Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and functionsGraphicsProgrammingSimulinkWhat is Simulink?Simulink is a softwarepackage for modeling,simulating, andanalyzing dynamicsystems. It supportslinear and nonlinearsystems, in continuousor discrete time, or ahybrid of the two. Type simulink in thecomm. win. or click onicon.Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and functionsGraphicsProgrammingSimulinkCreate an exampleFile New Model. Save thefoo.mdl file.You can now define a modelwith inputs, dynamics,controller, sensors andactuators.For now, just play with blocks.Double click to set parameters.This example just produces asin wave plot.Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and functionsGraphicsProgrammingSimulinkRun a simulationTo run a simulation,need to set thesimulation parameters.Duration, ODE solver,step size: depend on theproblem.Scopes are needed toplot the variables ofinterest.Elisa FrancoMatlab Tutorial, CDS110-101

OutlineIntroductionVariablesOperations and s was a short introduction to the main features of Matlab.Please always refer to the full product documentation! For otheronline tutorials, Google will pop out many of mlIcontrol tutorial: http://www.engin.umich.edu/group/ctm/I.Elisa FrancoMatlab Tutorial, CDS110-101

Matlab can be used both from the command window and by coding scripts. GUI's are available for specific tasks. Files created in Matlab end in .m, data can be saved in files that end in .mat (we will see how). Help: command window (see next slide), i.e. helpsubj or full product documentation. Elisa Franco Matlab Tutorial, CDS110-101