This action might not be possible to undo. Are you sure you want to continue?

BooksAudiobooksComicsSheet Music### Categories

### Categories

### Categories

Editors' Picks Books

Hand-picked favorites from

our editors

our editors

Editors' Picks Audiobooks

Hand-picked favorites from

our editors

our editors

Editors' Picks Comics

Hand-picked favorites from

our editors

our editors

Editors' Picks Sheet Music

Hand-picked favorites from

our editors

our editors

Top Books

What's trending, bestsellers,

award-winners & more

award-winners & more

Top Audiobooks

What's trending, bestsellers,

award-winners & more

award-winners & more

Top Comics

What's trending, bestsellers,

award-winners & more

award-winners & more

Top Sheet Music

What's trending, bestsellers,

award-winners & more

award-winners & more

Welcome to Scribd! Start your free trial and access books, documents and more.Find out more

Qian Wang Mechanical Engineering Penn State University

MATLAB Fundamentals Plotting Figures M-files ODE Solver Building Control Systems Time Response Root Locus Frequency Response / Bode Plot SIMULINK

1

Help Facility By typing “help”. . . To obtain solutions at specific times T0. The top menu bar can be used to open or write a M-file. you can save the workspace for later use by typing “save”.TSPAN. [T. .Interpolation and polynomials.numerical linear algebra.. .Programming language constructs.Getting Started Starting MATLAB Click the MATLAB icon on Windows to start MATLAB command window. .Data analysis and Fourier transforms. 'F' is a string containing the name of an ODE file.. Function F(T. you can get on-line help.Elementary math functions. MATLAB will provide some introductory remarks and pop up the MATLAB prompt >>. » help HELP topics: matlab\general matlab\ops matlab\lang matlab\elmat matlab\elfun matlab\specfun matlab\matfun matlab\datafun matlab\polyfun matlab\funfun matlab\sparfun … » help ode23 ODE23 Solve non-stiff differential equations. Before quitting.Y] = ODE23('F'.y) from time T0 to TFINAL with initial conditions Y0.General purpose commands. which gives an interactive interface.. . You can “save” with other “filenames” or to save only selected variables.Y) must return a column vector. low order method. “help <topics>”. . TFINAL]. . .Y0) with TSPAN = [T0 TFINAL] integrates the system of differential equations y' = F(t. Each row in solution array Y corresponds to a time returned in column vector T.Matrix functions . Once started..Specialized math functions. » save temp x y . T1. TFINAL (all increasing or all decreasing). . Saving working space Terminating a MATLAB session deletes the variables in the workspace.Sparse matrices.mat”. 2 .Function functions and ODE solvers. which saves the workspace as “matlab.Operators and special characters. use TSPAN = [T0 T1 . which will be addressed later.. .Elementary matrices and matrix manipulation.

Within a matrix.mat”.2000i » z = sqrt(y) z= 2.6529i » p = sin(pi/2) p= 1 Matrix Operations Matrix operations are fundamental to MATLAB.4210 + 8.4210 » y = x+8. For example 3 .”.421 x= 3.mat”. y” into “temp.4805 + 1. builds expressions with the usual arithmetic operators and precedence rules: » x = 3. and the rows are separated by semicolon”. type » load temp Exit Exit MATLAB by typing » quit or » exit Fundamental Expressions/Operations MATLAB uses conventional decimal notion.which saves the current variable “x.2i y= 3. To retrieve all the variables from the file named “temp. columns are separated by space.

^. Building Matrix Convenient matrix building functions are 4 . 4 5 6. and /. \. 7 8 9] A= 1 4 7 2 5 8 3 6 9 » B = ones(3. can be made to operate entry-wise by preceding them by a period. .3) B= 1 1 1 » A+B ans = 2 5 8 » A' ans = 1 2 3 4 5 6 7 8 9 3 6 9 4 7 10 1 1 1 1 1 1 The following matrix operations are available in MATLAB: + * ^ ‘ \ / addition subtraction matrix multiplication power transpose left division right division The operations.» A = [1 2 3.

2311 0.9501 0.6068 Retrieving part or an element of a matrix 5 .0000 0 0 0 1.6068 Matrices can be built from blocks.2311 0. For example.0000 0 0 0 1.0000 0 0 0 0 0 0 0. » A = eye(3) A= 1 0 0 0 1 0 0 0 1 » B = zeros(3.eye identity matrix zeros matrix of zeros ones matrix of ones diag diagonal matrix triu upper triangular part of a matrix tril lower triangular part of a matrix rand randomly generated matrix For example.1) C= 0.2) B= 0 0 0 0 0 0 » C = rand(3. » D = [A B C D] D= 1.9501 0.

9501 » max(max(D)) ans = 1 A few of these functions are: max. they operate essentially on a vector (row or column).0000 » D(1.. 6 . mean.6) ans = 0.e. :) ans = 1.» D(:.0000 1. min.5 E= 0. i. the maximum entry in a matrix D is given by max(max(D)). std. For example.5000 0 0 0 0 0.3000 0.6) ans = 0.3:0. sort.0000 0 0 0.1000 1. prod.7000 1.0000 1.4:1. » max(D) ans = 1. sum.9501 Other functions for colon notation: » E = 0. all. any.9501 0.9501 Vector Functions Certain functions in MATLAB are “vector functions”.6068 » D(1.2311 0.

6154 0.0185 0.1503 » inv(F) ans = 0.8214 0. 2-norm.3) F= 0.4565 0.7621 » eig(F) ans = 1.Matrix functions The most useful matrix functions are eig svd inv det size norm cond rank For example » F = rand(3.4860 0.4997 » rank(F) ans = 3 » cond(F) ans = 69.8913 0.0310 -0.7919 eigenvalues and eigenvectors singular value decomposition inverse determinant size 1-norm. F-norm condition number in the 2-norm rank 7 .7651 0.4447 0.

1385 -9.25).17.9446 -0.5560 -26.9689 8.5 -1 -1 -0. “plot(x.6579 -1.y2.y1. » plot(x.5 0 y -0. 'g--') » title('sin-cos plots') » xlabel('x=sin(t)') » ylabel('y') 1 sin-cos plots 0.2485 1.6802 -3. » figure(1) % open a figure and make it current. one alternative way is to use “hold on” and “hold off” commands. not necessarily » plot(x.y)” produces a graph of y versus x. » t = 0:pi/100:2*pi. » y2 = cos(t-0. » x = sin(t). » y1 = sin(t+0. If you specify two vectors as arguments.5 1 By plotting multiple figures on the graph.25). “plot (y)” produces a linear graph of the elements of y versus the index of the elements of y.5444 Plotting Figures Creating a Figure If y is a vector. 'r-') » hold on 8 .8760 14.y1.'r-'.5 0 x=sin(t) 0.x.

m”. Script files A script file consists of a sequence of normal MATLAB statements. -Linestyle point circle x-mark plus star solid dotted dashdot dashed Exporting a Figure 1) Cut and paste: click “Edit” at the top menu bar of the figure window. paste the figure wherever you want. markers.» plot(x. For example. and color Symbol y m c r g b w k Color yellow magenta cyan red green blue white black Symbol . Try it. 'g--') » hold off Other types of plots: loglog plot using logarithmic scales for both axes semilogx plot using a logarithmic scales for x-axis and linear scale for the y-axis semilogy figure out yourself Line styles. M-files MATLAB can execute a sequence of statements in a file. Such files are called “M-files” because they must have the file type of “.m” as the last part of their filename. o x + * : -. type all the commands for generating the figure into a single script file and save as “sineplot.y2. Then the MATLAB command “sineplot” will cause the statements in the file to be executed. 2) Save as a file: print –tiff –deps (print as a postscript file). then click “Copy Figure”. There are two types of M-files: script files and function files. Function files 9 . Type “help print” to find out more options.

5. 0.^2 + . We would like to generate a 2 by 3 random matrix between 1.5 » a = myrand(1.2507 Numerical Integration / ODE Solver Numerical Integration (Quadrature) To integrate sin(x) from 0 to pi/4.9). x = l + rand(row.m contains the statements function x = myrand(l. 1)”.7171 4. Differential Equation Solver MATLAB's functions for solving ordinary differential equations are ode23 – 2nd/3rd order Runge-Kutta method ode45 – 4th/5th order Runge-Kutta method 10 . try out “q = quad(‘hump’.2929 Create an M-file called hump.. The file myrand.01) + 1. 2. which will then have the same status as other MATLAB functions.3064 4./(x-. col) % generate uniformly-distributed random number matrix (row. y2. …) Here is a simple example. . Variables in a function files are by default local.7146 2.04) –7.* (u-l).You can create new functions specific to your problem. row. u. The function file will start with function [y1.] = Function Name (x1.2654 3./((x-.5 and 4. 3) a= 4.5.3). col).^2 + . x2. pi/4) q= 0. » q = quad('sin'. otherwise need to be declared as “global”. col) between low% bound l and upper-bound u.m function y = hump(x) y = 1. 4.0288 2. 0.

25]’. invoke ode23 t0 = 0. x0 = [0 0. SIMULINK is a comprehensive extension to MATLAB for the simulation of differential equations.x) xdot = zeros(2. [t0 tf]. function xdot = vdpol(t. we will address it later on. % Initial conditions [t. 11 . xdot(2) = x(1). Then create a function M-file containing these differential equations.First transform a high-order differential equation into a set of first-order differential equations.1). x) 3 2 1 0 -1 -2 -3 0 2 4 6 8 10 12 14 16 18 20 Type “help ode23” to find out all the other options. To simulate the differential equation defined in “vdpol” over the interval [0.*(1-x(2).x] = ode23(‘vdpol’.m”.20]. tf = 20. xdot(1) = x(1). plot (t. x0). 2 & x1 = x1 (1 − x 2 ) − x 2 & x 2 = x1 Create a file called “vdpol.^2)-x(2). For example.

5 For SISO models. 0 1 0].8 0 x2 -13.5 1. “num” and “den” are row vectors listing the numerator and denominator coefficients in descending powers of s by default. Type in A.1 0 1 x3 -4.1].3) ( s + 2. B. [1 15]). » sys_2 = SS(A.5 ------------------s^2 + 17. C.Setting Up Control Systems Creating transfer function Consider a single-input single-output system (SISO) given by G ( s) = 5( s + 5.1)( s + 15) You can create G(s) using “TF” in MATLAB.1 s + 31. » den = conv([1 2.5 -13. Creating state space model Create state-space models in MATLAB is analogous to creating transfer function.5. C. » num = 5*[1 5. » sys_1 = TF(num.1 -4. » D = 0. B. den) Transfer function: 5 s + 26.3]. 1. » A = [-23. D) a= x1 x2 x3 b= x1 x2 x3 u1 1 0 0 x1 -23. » C = [ 0 18 23]. » B = [1 0 0]'. D matrices and use command “SS”.5 0 0 12 .8 0 0.

4 -----------------------------s^3 + 23.1 8 x2 -3.58 s + 8.4 s + 41.c= y1 d= y1 u1 0 x1 0 x2 18 x3 23 Transformation between transfer function and state-space models It is easy to transform a transfer function model into a state-space model. or vice versa.25 x2 0.1 13 .5 s^2 + 23.82813 u1 4 0 x1 -17. 1) Transform sys_1 from transfer function model to state-space model » sys_1_ss = SS(sys_1) a= x1 x2 b= x1 x2 c= y1 d= y1 u1 0 x1 1.9375 0 2) Transform sys_2 from state-space model into transfer function model » sys_2_tf = TF(sys_2) Transfer function: 32.

Amplitude 14 .15 0.3 0.05 0 0 1 2 3 Time (sec. and a gain of 3. » sys_3 = zpk ([].Extract zero/pole/gain data.2 0.25 0.Other commands on building models and extract data from a model zpk . zpkdata .4 0. poles at s= -1+3i and s = -1-3i. ssdata .35 0.) 4 5 6 The other commands are impulse – for impulse response initial -. Computing and Plotting Time Response For example. tfdata .for initial response Type help to figure out how to use them. we would like to compute and plot step response for a system with no zeros.1 0.Create a zero/pole/gain model. [-1+3*i -1-3*i].Extract state-space matrices. 3) Zero/pole/gain: 3 --------------(s^2 + 2s + 10) » step (sys_3) Step Response 0.Extract numerator(s) and denominator(s).

Root Locus Plots For example.5 -2 -2. den) 15 . » bode(num.5 -6 -5 -4 -3 -2 Real Axis -1 0 1 2 Find out how to plot root locus for state-space model. » den = [1 4 9]. draw root locus plot for a transfer function model s+2 G(s) = 2 s + 4s + 9 » num =[1 2]. » den = [1 4 9]. den) 2.5 1 0. » rlocus(num.5 2 1.5 -1 -1. Frequency Domain Plots Bode Plot » num =[1 2].5 Imag Axis 0 -0.

which is much like drawing a block diagram. you can analyze it either by choosing options from the SIMULINK menus or by entering commands in MATLAB’s command window.Bode Diagrams -10 Phase (deg).2 Copyright (c) 1990-1998 by The MathWorks. Model definition uses the metaphor of a block diagram. Instead of drawing the individual blocks. Inc. you can rename it when you save it. The progress of a simulation can be viewed while the simulation is running. Magnitude (dB) -15 -20 0 -20 -40 -60 -1 0 1 10 10 10 Frequency (rad/sec) SIMULINK SIMULINK is a program for simulating dynamic systems. 16 . Select “New” from the “File” menu on its menu bar to open a new empty window labeled “Untitled”. and the final results can be made available in the MATLAB workspace when a simulation is complete. Notice that when you drag a block to a different window you drag only a copy of the block. Open the SIMULINK block library by entering the command » simulink in the MATLAB command window. After you define a model. blocks are copied from libraries of blocks. This command displays a new window containing icons for the subsystem blocks In1 Out1 Sources Blocksets & Toolboxes Sinks Discrete Linear Nonlinear Connections Demos Simulink Block Library 2. The new window is where you construct your system model by dragging blocks from their original location to the new window. It has two phases of use: model definition and model analysis.

change “list of signs” to “+-“. 17 .1. Click the block “Stiffness”. The spring-mass-damper system is taken from the text book. Draw lines to connect the blocks Draw lines to connect the blocks by moving the mouse pointer over a block’s port and holding down the left mouse button. Open libraries and copy blocks into your model window Click the window containing icons for subsystem blocks to make it active.6 on Pg. 137. rename the block as “Monitor output”. and then drag “Sum” into your model window from the “Linear” library. and then drag “Scope” block to your model window from the “Sink” library. and final value as 2. Double click “Sum”. • Double click “Sources”. rename one as “Velocity” and one as “Displacement”. set step time as 0. Making a split flow from a connection line is done by pressing the right mouse button and drag the new connection. select “flip block” from the “Format” menu to flip the orientation of the block “Stiffness”. • Double click “Sink”. • Copy two “Gain” blocks from the “Linear” library to your model window. and then drag “Step” block into your model window from the “Source” library. “Dynamic modeling and control of engineering systems”. initial value as 0. and then drag “Coulomb” block to your model window from the “Nonlinear” library. rename one into “Stiffness”. 1 Stiffness 1 Step Sum 1/m 1 s Velocity 1 s Displacement Monitor ouput Coulomb & Viscous Friction Change block parameters • Double click “Step”. • Double click “Nonlinear”. Figure 6. • Copy two “Integrators” blocks from the “Linear” library to your model window. • Double click “Linear”.Example: Building a simple SIMULINK model for a spring-mass-damper system with nonlinear friction. and one to “1/m”.

Click the “Monitor output” block to monitor your system output Simulation from the Command Line Any simulation run from the menu can also be run from the command line. set offset as 0. set the gain value as 1. Double click “Coulomb friction”.0.0. Double click “1/m” block.5 and gain as 1. use the command [t. y] = rk45(‘model’. the “Start” menu item becomes “Stop”. Other Ways to View Output Trajectories Besides using the “Scope” block. click the “properties” button next to the “print” button. Double click “Monitor output”. x. For example. Set simulation time: start time = 0. tfinal]). set the gain value as 1.5. If you select “Stop”. and Ymin as –0. output trajectories from SIMULINK can be plotted by • Return variables and the MATLAB plotting commands • Using “Workspace” blocks and the MATLAB plotting commands. the menu displays “Start” again. and stop time = 5.0 Save the system by selecting “Save” from the “File” menu Run a simulation by selecting “Start” from the “Simulation” menu While the simulation is running.0.5. set Ymax as 2. select “Parameters” from the “Simulation” menu.• • • • • Double click “Stiffness”. 18 . [tstart.8. Go back to the model window. where model is the name of the block diagram system you build.

3) Leonard. N. E. 19 . Inc. 4) Sigmon. K. and W. the MathWorks Inc. MATLAB Primer. University of Florida. Levine. Using MATLAB to Analyze and Design Control Systems.References 1) MATLAB User’s Guide. the MathWorks Inc.. 2) SIMULINK User’s Guide. Department of Mathematics. The Benjamin/Cummings Publishing Company. S.

Are you sure?

This action might not be possible to undo. Are you sure you want to continue?

We've moved you to where you read on your other device.

Get the full title to continue

Get the full title to continue listening from where you left off, or restart the preview.

scribd