 ### Transcription

Dynamics and VibrationsMATLAB tutorialSchool of EngineeringBrown UniversityThis tutorial is intended to provide a crash-course on using a small subset of the features of MATLAB. Ifyou complete the whole of this tutorial, you will be able to use MATLAB to integrate equations of motionfor dynamical systems, plot the results, and use MATLAB optimizers and solvers to make designdecisions.You can work step-by-step through this tutorial, or if you prefer, you can brush up on topics from the listbelow.If you are working through the tutorial for the first time, you should complete sections 1-13.6. You cando the other sections later, when they are needed. If you have taken EN30, you should be familiar withthe material in Sections 1-10: you can review these if you like, or skip directly to Section 11.1. What is MATLAB2. Starting MATLAB3. Basic MATLAB windows4. Simple calculations using MATLAB5. MATLAB help6. Errors associated with floating point arithmetic (and an example of a basic loop)7. Vectors in MATLAB7.1 Creating Vectors with a Loop7.2 Dot notation for operations on vectors7.3 Operations on vectors using a loop8. Matrices in MATLAB9. Plotting and graphics in MATLAB10. Working with M-files11. MATLAB Functions12. Organizing complex calculations as functions in an M-file13. Solving ordinary differential equations (ODEs) using MATLAB13.1 What is a differential equation?13.2 Solving a basic differential equation13.3 Solving a basic differential equation in an M-file13.4 Solving a differential equation with adjustable parameters13.5 Common errors13.6 Solving simultaneous differential equations13.7 Controlling the accuracy of solutions to differential equations13.8 Looking for special events in a solution13.9 How the ODE solver works13.10 Other MATLAB differential equation solvers14. Using MATLAB solvers and optimizers to make design decisions14.1 Using fzero to solve equations14.2 Simple unconstrained optimization problem14.3 Optimizing with constraints15. Reading and writing data to/from files16. Movies and animation

Select a convenient directory where you will be able to save your files.4. Simple calculations using MATLABYou can use MATLAB as a calculator. Try this for yourself, by typing the following into the commandwindow. Press ‘enter’ at the end of each line. x 4 y x 2 z factorial(y) w log(z)*1.e-05 format long w format long eng w format short w sin(pi)MATLAB will display the solution to each step of the calculation just below the command. Do you noticeanything strange about the solution given to the last step?Once you have assigned a value to a variable, MATLAB remembers it forever. To remove a value from avariable you can use the ‘clear’ statement - try clear a aIf you type ‘clear’ and omit the variable, then everything gets cleared. Don’t do that now – but it isuseful when you want to start a fresh calculation.MATLAB can handle complex numbers. Try the following z x i*y real(z) imag(z) conj(z) angle(z) abs(z)You can even do things like log(z) sqrt(-1) log(-1)Notice that: Unlike MAPLE, Java, or C, you don’t need to type a semicolon at the end of the line (To properlyexpress your feelings about this, type load handel and then sound(y,Fs) in the commandwindow). If you do put a semicolon, the operation will be completed but MATLAB will not print the result.This can be useful when you want to do a sequence of calculations.

Special numbers, like pi’ and ‘i’ don’t need to be capitalized. But beware – you often use i as acounter in loops – and then the complex number i gets re-assigned as a number. You can also dodumb things like pi 3.2 (You may know that in 1897 a bill was submitted to the Indianalegislature to declare pi 3.2 but fortunately the bill did not pass). You can reset these specialvariables to their proper definitions by using clear i or clear piThe Command History window keeps track of everything you have typed. You can double leftclick on a line in the Command history window to repeat it, or right click it to see a list of otheroptions.The output in the command window looks like crap. MATLAB is not really supposed to be usedlike this. We will discuss a better approach later.If you screw up early on in a sequence of calculations, there is no quick way to fix your error,other than to type in the sequence of commands again. You can use the ‘up arrow’ key to scrollback through a sequence of commands. Again, there is a better way to use MATLAB that getsaround this problem.If you are really embarrassed by what you typed, you can right click the command window anddelete everything (but this will not reset variables). You can also delete lines from the Commandhistory, by right clicking the line and selecting Delete Selection. Or you can delete the entireCommand History.You can get help on MATLAB functions by highlighting the function, then right clicking the lineand selecting Help on Selection. Try this for the sqrt(-1) line.5. MATLAB helpHelp is available through the online manual – Click on the question-mark in the strip near the top right ofthe window).By default the help window opens inside theMATLAB GUI, but you can drag it out so itoccupies a new window on your desktop.If you already know the name of the MATLABfunction you want to use the help manual is quitegood – you can just enter the name of the functionin the search, and a page with a good number ofexamples usually comes up.It is morechallenging to find out how to do something, butmost of the functions you need can be found byclicking on the MATLAB link on the main pageand then following the menus that come up onsubsequent pages.

a [9,8,7,6,5,4,3,2,1] b [1,2,3,4,5,6,7,8,9]You can add, subtract, and evaluate the dot product of vectors that are not 3D, but you can’t take a crossproduct. Try the following a b dot(a,b) cross(a,b)In MATLAB, vectors can be stored as either a row of numbers, or a column of numbers. So you couldalso enter the vector a as a [9;8;7;6;5;4;3;2;1]to produce a column vector.You can turn a row vector into a column vector, and vice-versa by b transpose(b)7.1 Creating vectors with a loopYou can create a vector containing regularly spaced data points very quickly with a loop. Try for i 1:11v(i) 0.1*(i-1);end vThe for end loop repeats the calculation with each value of i from 1 to 11. Here, the “counter”variable i now is used to refer to the ith entry in the vector v, and also is used in the formula itself.As another example, suppose you want to create a vector v of 101 equally spaced points, starting at 3 andending at 2*pi, you would use for i 1:101v(i) 3 (2*pi-3)*(i-1)/100;end v7.2 Dot notation for operations on vectorsYou can often manipulate the numbers in a vector using simple MATLAB commands. For example, ifyou type sin(v)MATLAB will compute the sin of every number stored in the vector v and return the result as anothervector. This is useful for plots – see section 11.You have to be careful to distinguish between operations on a vector (or matrix, see later) and operationson the components of the vector. For example, try typing v 2This will cause MATLAB to bomb, because the square of a row vector is not defined. But you can type v. 2(there is a period after the v, and no space). This squares every element within v.You can also do things like v. /(1 v)

(see if you can work out what this does).7.3 Operations on vectors using a loopI personally avoid using the dot notation – mostly because it makes code hard to read. Instead, I generallydo operations on vector elements using loops. For example, instead of writing w v. 2, I would use for i 1:length(v)w(i) v(i) 2;end wHere, ‘for i 1:length(v)’ repeats the calculation for every element in the vector v. The functionlength(vector) determines how many components the vector v has (101 in this case).Using loops is not elegant programming, and slows down MATLAB. Purists (like CS40 TAs) object to it.But I don’t care. For any seriously computationally intensive calculations I would use a programminglanguage like C or Fortran95, not MATLAB. Programming languages like Java, C , or Python arebetter if you need to work with complicated data structures.8. Matrices in MATLABHopefully you know what a matrix is If not, it doesn’t matter - for now, it is enough to know that amatrix is a set of numbers, arranged in rows and columns, as shown belowColumn 2 1 5 3 9543206082 6 5 7 row 1row 4Column 3A matrix need not necessarily have the same numbers of rows as columns, but most of the matrices wewill encounter in this course do. A matrix of this kind is called square. (My generation used to call ourprofessors and parents square too, but with hindsight it is hard to see why. ‘Lumpy’ would have beenmore accurate).You can create a matrix in MATLAB by entering the numbers one row at a time, separated bysemicolons, as follows A [1,5,0,2; 5,4,6,6;3,3,0,5;9,2,8,7]You can extract the numbers from the matrix using the convention A(row #, col #). Try A(1,3) A(3,1)You can also assign values of individual array elements A(1,3) 1000

There are some short-cuts for creating special matrices. Try the following B ones(1,4) C pascal(6) D eye(4,4) E zeros(3,3)The ‘eye’ command creates the ‘identity matrix’ – this is the matrix version of the number 1. You canuse help pascalto find out what pascal does.MATLAB can help you do all sorts of things to matrices, if you are the sort of person that enjoys doingthings to matrices. For example1. You can flip rows and columns with B transpose(A)2. You can add matrices (provided they have the same number of rows and columns C A BTry also C – transpose(C)A matrix that is equal to its transpose is called symmetric3. You can multiply matrices – this is a rather complicated operation, which will be discussed inmore detail elsewhere. But in MATLAB you need only to type D A*B to find the product ofA and B. Also try the following E A*B-B*A F eye(4,4)*A - A4. You can do titillating things like calculate the determinant of a matrix; the inverse of a matrix, theeigenvalues and eigenvectors of a matrix. If you want to try these things det(A) inv(A) eig(A) [W,D] eig(A)You can find out more about these functions, and also get a full list of MATLAB matrixoperations in Linear Algebra page of the help menu.

MATLAB can also calculate the product of a matrix and a vector. This operation is used very frequentlyin engineering calculations. For example, you can multiply a 3D column vector by a matrix with 3 rowsand 3 columns, as follows v [4;3;6] A [3,1,9;2,10,4;6,8,2] w A*vThe result is a 3D column vector. Notice that you can’t multiply a 3D row vector by a 3x3 matrix. Trythis v [4,3,6] w A*vIf you accidentally enter a vector as a row, you can convert it into a column vector by using v transpose(v)MATLAB is also very good at solving systems of linear equations. For example, consider the equations3 x1 4 x2 7 x3 65 x1 2 x2 9 x3 1 x1 13 x2 3 x3 8This system of equations can be expressed in matrix form asAx b x1 3 4 7 6 A 5 2 9 x x2 b 1 x3 1 13 3 8 To solve these in MATLAB, you would simply type A [3,4,7;5,2,-9;-1,13,3] b [6;1;8] x A\b(note the forward-slash, not the back-slash or divide sign) You can check your answer by calculating A*xThe notation here is supposed to tell you that x is b ‘divided’ by A – although division’ by a matrix hasto be interpreted rather carefully. Try also x transpose(b)/AThe notation transpose(b)/A solves the equations xA b , where x and b are row vectors. Again, you cancheck this with x*A(The answer should equal b, (as a row vector) of course)MATLAB can quickly solve huge systems of equations, which makes it useful for many engineeringcalculations. The feature has to be used carefully because systems of equations may not have a solution,or may have many solutions – MATLAB has procedures for dealing with both these situations but if youdon’t know what it’s doing you can get yourself into trouble. For more info on linear equations check thesection of the manual below

9. Plotting and graphics in MATLAB This is an important section of this tutorialPlotting data in MATLAB is very simple. Try the following for i 1:101 x(i) 2*pi*(i-1)/100; end y sin(x) plot(x,y)MATLAB should produce something that lookslike this (the 2014b MATLAB version producescurves with a different color scheme and linethickness to 2012b)MATLAB lets you edit and annotate a graphdirectly from the window. For example, youcan go to Tools Edit Plot, then double-clickthe plot. A menu should open up that will allowyou to add x and y axis labels, change the rangeof the x-y axes; add a title to the plot, and so on.You can change axis label fonts, the linethickness and color, the background, and so on – usually by double-clicking what you want to change andthen using the pop-up editor. You can export figures in many different formats from the File Save Asmenu – and you can also print your plot directly. Play with the figure for yourself to see what you can do.

Helpful Hint: If you annotate a plot by hand, youcan make MATLAB generate the code to re-createyour annotated plot automatically by going to File Generate Code. This is useful when you write yourown scripts and want to label plots automatically.To plot multiple lines on the same plot you can use y sin(x) plot(x,y) hold on y sin(2*x) plot(x,y)Alternatively, you can use y(1,:) sin(x); y(2,:) sin(2*x); y(3,:) sin(3*x); plot(x,y)Here, y is a matrix. The notation y(1,:) fills the first row of y, y(2,:) fills the second, and so on. Thecolon : ensures that the number of columns is equal to the number of terms in the vector x. If you prefer,you could accomplish the same calculation in a loop: for i 1:length(x) y(1,i) sin(x(i)); y(2,i) sin(2*x(i)); y(3,i) sin(3*x(i)); end plot(x,y)Notice that when you make a new plot, it always wipes out the old one. If you want to create a new plotwithout over-writing old ones, you can use figure plot(x,y)The ‘figure’ command will open a new window and will assign a new number to it (in this case, figure 2).If you want to go back and re-plot an earlier figure you can use figure(1) plot(x,y)If you like, you can display multiple plots in the same figure, by typing newaxes axes; plot(x,y)The new plot appears over the top of the old one, but you can drag it away by clicking on the arrow tooland then clicking on any axis or border of new plot. You can also re-size the plots in the figure windowto display them side by side. The statement ‘newaxes axes’ gives a name (or ‘handle’) to the new axes,so you can select them again later. For example, if you were to create a third set of axes yetmoreaxes axes; plot(x,y)you can then go back and re-plot newaxes’ by typing axes(newaxes); plot(x,y)Doing parametric plots is easy. For example, try for i 1:101 t(i) 2*pi*(i-1)/100; end x sin(t); y cos(t); plot(x,y)

MATLAB has vast numbers of different 2D and 3D plots. For example, to draw a filled contour plot ofthe function z sin(2π x)sin(2π y ) for 0 x 1, 0 y 1 , you can use for i 1:51 x(i) (i-1)/50; y(i) x(i); end z transpose(sin(2*pi*y))*sin(2*pi*x); figure contourf(x,y,z)The first two lines of this sequence should be familiar: they create row vectors of equally spaced points.The third needs some explanation – this operation constructs a matrix z, whose rows and columns satisfyz(i,j) sin(2*pi*y(i)) * sin(2*pi*x(j)) for each value of x(i) and y(j).If you like, you can change the number of contour levels contourf(x,y,z,15)You can also plot this data as a 3D surface using surface(x,y,z)The result will look a bit strange, but you can click on the ‘rotation 3D’ button (the little box with acircular arrow around it ) near the top of the figure window, and then rotate the view in the figure withyour mouse to make it look more sensible.You can find out more about the different kinds of MATLAB plots in the section of the manual shownbelow

10. Working with M filesSo far, we’ve run MATLAB by typing into the command window. This is OK for simple calculations,but it is usually better to type the list of commands you plan to execute into a file (called an M-file), andthen tell MATLAB to run all the commands together. One benefit of doing this is that you can fix errorseasily by editing and re-evaluating the file. But more importantly, you can use M-files to write simpleprograms and functions using MATLAB.To create an M-file, simply press the ‘New Script’ button on the main MATLAB window.This will open a new window for the matlab script editor, as shown belowNow, type the following lines into the editor (see the screenshot):for i 1:101theta(i) -pi 2*pi*(i-1)/100;rho(i) 2*sin(5*theta(i));endfigurepolar(theta,rho)You can make MATLAB execute these statements by:1. Pressing the green arrow labeled ‘Run’ near the top of the editor window – this will first save thefile (MATLAB will prompt you for a file name – save the script in a file called myscript.m), andwill then execute the file.