Matlab for Control System

download Matlab for Control System

of 205

description

Matlab For Control Systems

Transcript of Matlab for Control System

MATLAB MODULE 1

MATLAB Window Environment and the Base Program

Starting MATLAB

On the Windows desktop, the installer usually creates a shortcut icon for starting MATLAB; double-clicking on this icon opens MATLAB desktop.

The MATLAB desktop is an integrated development environment for working with MATLAB suite of toolboxes, directories, and programs. We see in Fig. M1.1 that there are four panels, which represent:1. Command Window 2. Current Directory 3. Workspace 4. Command History A particular window can be activated by clicking anywhere inside its borders.

Fig. M1.1 MATLAB Desktop (version 7.0, release 14)Desktop layout can be changed by following Desktop --> Desktop Layout from the main menu as shown in Fig. M1.2 (Default option gives Fig. M1.1).

Fig. M1.2 Changing Desktop Layout to History and Command Window option

Command Window We type all our commands in this window at the prompt ( >> ) and press return to see the results of our operations. Type the command ver on the command prompt to get information about MATLAB version, license number, operating system on which MATLAB is running, JAVA support version, and all installed toolboxes. If MATLAB don't regard to your speed of reading and flush the entire output at once, just type more on before supplying command to see one screen of output at a time. Clicking the What's New button located on the desktop shortcuts toolbar, opens the release notes for release 14 of MATLAB in Help window. These general release notes give you a quick overview of what products have been updated for Release 14.

Working with Command Window allows the user to use MATLAB as a versatile scientific calculator for doing online quick computing. Input information to be processed by the MATLAB commands can be entered in the form of numbers and arrays. As an example of a simple interactive calculation, suppose that you want to calculate the torque ( T ) acting on 0.1 kg mass ( m ) at swing of the pendulum of length ( l ) 0.2 m. For small values of swing, T is given by the formula . This can be done in the MATLAB command window by typing: >> torque = 0.1*9.8*0.2*pi/6 MATLAB responds to this command by:

torque = 0.1026 MATLAB calculates and stores the answer in a variable torque (in fact, a array) as soon as the Enter key is pressed. The variable torque can be used in further calculations. is predefined in MATLAB; so we can just use pi without declaring it to be 3.14.Command window indicating these operations is shown in Fig. M1.3.

Fig. M1.3 Command Window for quick scientific calculations ( text in colored boxes corresponds to explanatory notes ).If any statement is followed by a semicolon,

>> m = 0.1; >> l = 0.2; >> g = 9.8; the display of the result is suppressed. The assignment of the variable has been carried out even though the display is suppressed by the semicolon. To view the assignment of a variable, simply type the variable name and hit Enter. For example:>> torque=m*g*l*pi/6; >> torque torque = 0.1026 It is often the case that your MATLAB sessions will include intermediate calculations whose display is of little interest. Output display management has the added benefit of increasing the execution speed of the calculations, since displaying screen output takes time.Variable names begin with a letter and are followed by any number of letters or numbers (including underscore). Keep the name length to 31 characters, since MATLAB remembers only the first 31 characters. Generally we do not use extremely long variable names even though they may be legal MATLAB names. Since MATLAB is case sensitive, the variables A and a are different.When a statement being entered is too long for one line, use three periods, , followed by to indicate that the statement continues on the next line. For example, the following statements are identical (see Fig. M1.4).

>> x=3-4*j+10/pi+5.678+7.890+2^2-1.89 >> x=3-4*j+10/pi+5.678... +7.890+2^2-1.89 + addition, subtraction, * multiplication, / division, and ^ power are usual arithmetic operators.

The basic MATLAB trigonometric commands are sin, cos, tan, cot, sec and csc. The inverses , etc., are calculated by asin, acos, etc. The same is true for hyperbolic functions. Some of the trigonometric operations are shown in Fig M1.5.

Variables j = and i = are predefined in MATLAB and are used to represent complex numbers.

Fig. M1.4 Command Window with example operations

Fig. M1.5 Example trigonometric calculations

MATLAB representation of complex number :

or The later case is always interpreted as a complex number, whereas, the former case is a complex number in MATLAB only if j has not been assigned any prior local value.

MATLAB representation of complex number :

or or In Cartesian form, arithmetic additions on complex numbers are as simple as with real numbers. Consider two complex numbers and . Their sum is given by

For example, two complex numbers and can be added in MATLAB as:

>> z1=3+4j; >> z2=1.8+2j; >> z=z1+z2 z = 4.8000 + 6.0000i Multiplication of two or more complex numbers is easier in polar/complex exponential form. Two complex numbers with radial lengths and are given with angles and rad. We change to radians to give rad= rad. The complex exponential form of their product is given by

This can be done in MATLAB by:

>> theta1=(35/180)*pi; >> z1=2*exp(theta1*j); >> z2=2.5*exp(0.25*pi*j); >> z=z1*z2 z = 0.8682 - 4.9240j Magnitude and phase of a complex number can be calculated in MATLAB by commands abs and angle. The following MATLAB session shows the magnitude and phase calculation of complex numbers and .

>> abs(5*exp(0.19*pi*j)) ans = 5 >> angle(5*exp(0.19*pi*j)) ans = 0.5969 >> abs(1/(2+sqrt(3)*j)) ans = 0.3780 >> angle(1/(2+sqrt(3)*j)) ans = -0.7137 Some complex numbered calculations are shown in Fig. M1.6.Fig. M1.6 Example complex numbered calculations

The mathematical quantities and are calculated with exp(x), log10(x), and log(x), respectively.

All computations in MATLAB are performed in double precision . The screen output can be displayed in several formats. The default output format contains four digits past the decimal point for nonintegers. This can be changed by using the format command. Remember that the format command affects only how numbers are displayed, not how MATLAB computes or saves them. See how MATLAB prints in different formats.

Format command at MATLAB prompt Display format

format short 31.4159

format short e3.1416e+001

format long 31.41592653589793

format long e 3.141592653589793e+001

format short g 31.416

format long g 31.4159265358979

format bank 31.42

The following exercise will enable the readers to quickly write various mathematical formulas, interpreting error messages, and syntax related issues.

Excersisei. By using arbitrary values of , check that .

ii. Verify with a few arbitrary values of that .

iii. Verify with a few arbitrary values of that .

iv. For t =0, 2, 5, 7, 12 and 25, find the value of the function .

Exercise M1.2 1. Try entering complex number in MATLAB as 3+j4 and check the answer. Initialize and then enter 3+4j, 3+j*4, and 3+4*j and check the various answers. Interpret messages given by MATLAB.

2. Calculate magnitude and phase of the following complex numbers for using MATLAB.

a.

b. .

3. Use MATLAB to calculate the magnitude and phase of for

Exercise M1.3 1. Calculate the quantity for .

2. Calculate for .

Note: Inf, and NaN are predefined in MATLAB. NaN stands for Not-a-Number and results from undefined operations like 0/0. Inf represents .

Current Directory Window

This window (Fig. M1.7) shows the directory, and files within the directory which are in use currently in MATLAB session to run or save our program or data. The default directory is C:\MATLAB7\work'. We can change this directory to the desired one by clicking on the square browser button near the pull-down window. Fig. M1.7 Current directory window

One can also use command line options to deal with directory and file related issues. Some useful commands are shown in Table M1.1.

Table M1.1Command Usage

cd, pwd To see the current directory

cd .. To go one directory back from the current directory

cd \ To go back to the root directory

cd dir_name To change to the directory named dir_name

ls or dir To see the list of files and subdirectories within the current directory

what Lists MATLAB-specific files in the directory. MATLAB specific files are with the extensions .m, .mat, .mdl, .mex, and .p.

mkdir (parentdir,dir_name) mkdir dir_name Makes new directory with the name dir_name in the parent directory specified by parentdir . When supplied with only dir_name, it creates new directory within the current directory

delete file_name delete *.m Deletes file from the current directory. Deletes all m-files from the current directory.

MATLAB desktop snapshot showing selected commands from Table M1.1 are shown in Fig. M1.8.

WorkspaceWorkspace window shows the name, size, bytes occupied, and class of any variable defined in the MATLAB environment. For example in Fig.M1.9, b' is 1 X 4 size array of data type double and thus occupies 32 bytes of memory. Double-clicking on the name of the variable opens the array editor (Fig. M1.10). We can change the format of the data (e.g., from integer to floating point), size of the array (for example, for variable A, from 3 X 4 array to 4 X 4 array) and can also modify the contents of the array.

Fig. M1.8 Example directory related commands

If we right-click on the name of a variable, a menu pops up, which shows various operations for the selected variable, such as: open the array editor, save selected variable for future usage, copy, duplicate, and delete the variable, rename the variable, editing the variable, and various plotting options for the selected variable.

Fig. M1.9 Entries in the Workspace

Fig. M1.10 Array editor window

Workspace related commands are listed in Table M1.2. Table M1.2Command Usage

who Lists variables currently in the workspace

whos Lists more information about each variable including size, bytes stored in the computer, and class type of the variables

clear Clears the workspace. All variables are removed

clear all Removes all variables and functions from the workspace. This can also be done by selecting Edit from the main menu bar and then clicking the option Clear Workspace .

clear var1 var2 Removes only var1 and var2 from the workspace.

For example, see the following MATLAB session for the use of who and whos commands. >> whoYour variables are:A b>> whos NameSizeBytesClass

A3x496double array

b1x432double array

Grand total is 16 elements using 128 bytes

Command History WindowThis window (Fig. M1.11) contains a record of all the commands that we type in the command window. By double-clicking on any command, we can execute it again. It stores commands from one MATLAB session to another, hierarchically arranged in date and time. Commands remain in the list until they are deleted.

Fig. M1.11 Command history window

Commands can also be recalled with the up-arrow key. This helps in editing previous commands.

Selecting one or more commands and right-clicking them, pops up a menu, allowing users to perform various operations such as copy, evaluate, or delete, on the selected set of commands. For example, two commands are being deleted in Fig. M1.12. Getting Help MATLAB provides hundreds of built-in functions covering various scientific and engineering computations. With numerous built-in functions, it is important to know how to look for functions and how to learn to use them.

For those who want to look around and get a feel for the MATLAB computing environment by clicking and navigating through what catches their attention, a window- based help is a good option. To activate the Help window, type helpwin or helpdesk on command prompt or start the Help Browser (Fig. M1.13) by clicking the icon from the desktop toolbar.

Fig. M1.12 Command history window with two commands being deleted

If you know the exact name of a command, type help commandname to get detailed task-oriented help. For example, type help helpwin in the command window to get the help on the command helpwin .

If you don't know the exact command, but (atleast !) know the keyword related to the task you want to perform, the lookfor command may assist you in tracking the exact command. The help command searches for an exact command name matching the keyword, whereas the lookfor command searches for quick summary information in each command related to the keyword. For example, suppose that you were looking for a command to take the inverse of a matrix. MATLAB does not have a command named inverse; so the command help inverse will not work. In your MATLAB command window try typing lookfor inverse to see the various commands available for the keyword inverse.

MATLAB has a wonderful demonstration program that shows its various features through interactive graphical user interface. Type demo at the MATLAB prompt to invoke the demonstration program (Fig. M1.14) and the program will guide you throughout the tutorials.

Fig. M1.13 Help browser

Fig. M1.14 Demonstration Window

Elementary Matrices Basic data element of MATLAB is a matrix that does not require dimensioning. To create the matrix variable in MATLAB workspace, type the statement (note that any operation that assigns a value to a variable, creates the variable, or overwrites its current value if it already exists).

>> A=[8 1 6 2;3 5 7 4;4 9 2 6] The blank spaces (or commas) around the elements of the matrix rows separate the elements. Semicolons separate the rows. For the above statement, MATLAB responds with the display

A = 8 1 6 2 3 5 7 4 4 9 2 6 Vectors are special class of matrices with a single row or column. To create a column vector variable in MATLAB workspace, type the statement

>> b=[1; 1; 2; 3] b = 1 1 2 3 To enter a row vector, separate the elements by a space or comma ' , '. For example:

>> b=[1,1,2,3] b = 1 1 2 3 We can determine the size of the matrices (number of rows, number of columns) by using the size command.

>> size(A) ans =3 4The command size, when used with the scalar option, returns the length of the dimension specified by the scalar. For example, size (A,1) returns the number of rows of A and size(A,2) returns the number of columns of A.

>> size(A,1) ans = 3 >> size(A,2) ans = 4 For matrices, the length command returns either number of rows or number of columns, whichever is larger. For example,

>> length(A) ans = 4 For vectors, length command can be used to determine its number of elements.

>> length(b) ans = 4 The use of colon ( : ) operator plays an important role in MATLAB. This operator may be used to generate a row vector containing the numbers from a given starting value xi, to the final value xf, with a specified increment dx, e.g., x=[xi:dx:xf] >> x=[0:0.1:1] x = Columns 1 through 7 0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000 Columns 8 through 11 0.7000 0.8000 0.9000 1.0000 By default, the increment is taken as unity.

To generate linearly equally spaced samples between x1 and x2, use the command linspace(x1,x2) . By default, 100 samples will be generated. The command linspace (x1,x2, N) allows the control over number of samples to be generated. See the example below.

>> x=linspace(0,1,11) x = Columns 1 through 6 0 0.1000 0.2000 0.3000 0.4000 0.5000 Columns 7 through 11 0.6000 0.7000 0.8000 0.9000 1.0000 Learn how to generate logarithmically spaced vector using the command logspace .

The colon operator can also be used to subscript matrices. For example, A(:,j) is the jth column of A, and A(i,:) is the ith row of A. Observe the following MATLAB session.

>> A=[8 1 6 2;3 5 7 4;4 9 2 6]; >> A(2,:) ans = 3 5 7 4 >> A(3,2:4) ans = 9 2 6 >> A(1,3) ans = 6 >> B=A(1:3,2:3) B = 1 6 5 7 9 2 >> A(:,3)=[ ] A = 8 1 2 3 5 4 4 9 6 Manipulating matrices is almost as easy as creating them. Try the following operations:

>> A+3 >> A-3 >> A*3 >> A/3 When you add/subtract/multiply/divide a vector/matrix by a number (or by a variable with a number assigned to it), MATLAB assumes that all elements of vector/matrix should be individually operated on.

Table M1.3 provides the list of basic operations on any two arbitrary matrices A and B and their dimensional requirements.

Table M1.3 Basic matrix operations OperationOperatorExampleNotes

Plus+A+BMust be of same dimensions

Minus-A-BMust be of same dimensions

Multiply*A*BMust be of compatible dimensions

Multiply (element-by-element).*A.*BMust be of same dimensions; multiplies element aij with element bij

Divide (element-by-element) ./A./BMust be of same dimensions; divides element aij by element bij

Divide (element-by-element) .\A.\BMust be of same dimensions; divides element bij by element aij

Matrix power ^A^kk must be a constant, A must be a square matrix

Matrix power (element-by-element).^A.^kk is a constant, A can be of any dimensions;gives (aij)k

Example M1.1 To find the solution of the following set of linear equations:

we write the equations in the matrix form as

where

is the matrix of coefficients of x1, x2 and x3

is the column vector which will contain the solutions x1, x2 and x3

is the column vector of values on the right-hand side

The solution vector

where stands for adjoint of matrix and stands for determinant of The determinant of matrix

is a scalar-valued function of . It is found through the use of minors and cofactors.

The minor mij of the element aij is the determinant of a matrix of order obtained from by removing the row and column containing aij. The cofactor cij of the element aij is defined by the equation

Determinants can be evaluated by an expansion that reduces the evaluation of an determinant down to the evaluation of a string of determinants, namely the cofactors. Selecting an arbitrary row k of matrix or arbitrary column l of matrix , we have

or

The adjoint of matrix is found by replacing each element aij of matrix by its cofactor and then transposing.

Following MATLAB commands solve the given set of simultaneous linear equations.

>> A = [2 5 -3; 3 -2 4; 1 6 -4]; >> b = [6; -2; 3]; >> x = inv(A) * b x = 4.8333 -4.5833 -6.4167

Exercise M1.4

Consider three matrices A, B, and C given below. Perform the following operations: A+B, B-C, A*C, A.*B, A./C, A.\B, A./B, (B*C)^3, and C.^3. Countercheck MATLAB answers manually. Try to interpret errors, if any.

Exercise M1.5 Create a vector t with 10 elements 1,2,.,10. Calculate for and , where .

Exercise M1.6

Create a vector t with initial time and final time with an interval of 0.05. Calculate

i. ii.

Flow Control FunctionsThere are many flow control functions in MATLAB. The for function in MATLAB provides a mechanism for repeatedly executing a series of statements a given number of times. The for function connected to an end statement sets up a repeating circulation loop. An important point is that each for must be matched with an end . The break statement provides exit jump out of loop.

The while function in MATLAB allows a mechanism for repeatedly executing a series of statements an indefinite number of times, under control of a logical condition.

The function if evaluates a logical expression and executes a group of statements based on the value of the expression. The else statement further conditionalizes the if statement.

Plotting

MATLAB is an outstanding tool for visualization. In the following, we will learn how to create and print simple plots.We are going to plot sinusoidal oscillations with exponential decay. To do this, first generate the data ( x- and y- coordinates). x- coordinate in this case is time steps. Let the initial time =0 sec and final time =10 sec with an interval of 0.05 sec. y- coordinate is the value of sinusoidal oscillations represented by . This plot can be generated by entering the following commands.

>> t=0:0.05:10; % Generating time steps >> yt=exp(-t/2).*sin(2*pi*t); %Calculate y(t ) >> plot(t,yt); %Plot t vs. y(t ) >> grid on; %Generating grids on x- and y-coordinates >> xlabel('Time Steps: t --->'); %Labeling x-axis >> ylabel('Sinusoid with exponential decay: y(t) --->'); %Labeling y-axis >> title('Plotting exp(-t/2)*sin(2*pi*t)'); %Put a title on the plot

Response is shown in graphics or figure window snapshot (Fig. M1.15).Arguments of the xlabel, ylabel, and title commands are text strings. Text strings are entered within single-quote characters. Lines beginning with % are comments; these lines are not executed. The print command sends the current plot to the printer connected to your computer.Rather than displaying the graph as a continuous curve, one can show the unconnected data points. To display the data points with small stars, use plot(t,yt,'*'). To show the line through the data points in red color as well as the distinct data points, one can combine the two plots with the command plot(t,yt,'r',t,yt,'*'). To learn more about plot options, type help plot on the MATLAB prompt and hit return.One can also produce multiple plots in a single window. Enter the following sequence of commands to your MATLAB command window and observe the resultant figure (Fig. M1.16).

Fig. M1.15 Plotting sinusoid with exponential decay

>> subplot(3,1,1);plot(sin(2*pi*t)); >> title('plot of sin(2*pi*t)'); >> subplot(3,1,2);plot(exp(-t/2)); >> title('plot of exp(-t/2)'); >> subplot(3,1,3);plot(exp(-t/2).*sin(2*pi*t)); >> title('multiply above two plots to get this');

Fig. M1.16 Plotting multiple plots in a single figure window

The command subplot(m,n,p) breaks the figure window into an m-by-n matrix of small axes and selects the pth axes for the current plot. Labeling, title, and grid commands should be given immediately after the particular subplot command to apply them to that subplot. Learn more about subplot using help subplot . Click on the Plot Editor icon once and then double click anywhere in the plot to open the Property Editor - Axes window (Fig M1.17). Using this property editor, title, axes, scale etc... of the plot can be changed.

Double clicking anywhere exactly on the curve opens the Property Editor Lineseries (Fig M1.18). From this, plot type can be changed on the spot. Available plot options are: Line, Area, Bar, Stairs, and Stem. Line width and markers can be changed by pull down menu Line and Marker.

Fig. M1.17 Axes property editor

Fig. M1.18 Lineseries property editor

Exercise M1.7

Generate 50 linearly spaced time steps between 0 and 10. Calculate for:

1. and ,3, and 5. Plot all the three curves in a single figure.

2. k =3 and . Plot all the three curves in a single figure.

Both the plots should be with respect to time. In both the plots, mark each curve with its k and values ( Hint: Use Insert Text Box option from main menu bar). From the main menu bar, choose Tools Edit Plot and then click anywhere on a curve. Plot Editor will open. Try several available options. Further to this, do the following:

1. Create legends for both the plots.

2. Use zoom-in and zoom-out tools.

3. Rotate plots using 3D rotation tool.

4. Click on the Data Cursor icon. Move mouse pointer anywhere in the graph sheet. A cross-hair cursor will appear. Clicking the cross-hair on the curve will give corresponding and axis values. Use Data Cursor to observe values at various time steps.

Exercise M1.8

Assign 0.5, , and to , respectively. Calculate for t = [0:0.1:10].

Obtain three plots for . Title the graph and label the Draw

all the three plots on the same graph sheet and mark each curve with appropriate value.

Exercise M1.9

1. Study the commands semilogx, semilogy, and loglog using help command.

2. Consider the complex number . Using MATLAB, generate the following two plots on semilog graph sheet for . Use subplot. Title both the plots, label the axes, and generate grid.

a) b)

Hint: Use logspace command to generate 100 logarithmically spaced samples of between 0.01 and 1000 rad/sec. Use abs and angle commands for calculations as per ii(a) and ii(b) given above for each Use semilogx to plot.

Script files (M-files)

Type edit on MATLAB prompt and hit enter (or follow File New M-File option from the main menu bar or click on icon in main toolbar). An Editor/Debugger window will open. This is where you write, edit, create, can run from, and save your own programs (user created script files with sequences of MATLAB commands) in files called M - files . An example M-file is shown in Fig. M1.19.

Create the same file in your MATLAB editor and then use the option File Save or File Save As to save the file with the name decayed_sin.m in current working directory. You can save all files into your personalized directory. If your personal directory is immediately below the directory in which the MATLAB application program is installed ( e.g. , c:\MATLAB7p0), then all user written files are automatically accessible to MATLAB. If you want to store files somewhere else, then you need to specify the path to the files using the path or addpath command, or change the current working directory to the desired directory before you run the program. For example, your script file is in the directory my_dir, which is not the current working directory of the MATLAB. If the location of my_dir is c:\docume~1\control\ my_dir ', it can be included in the MATLAB search path by:

>> path(path, c:\docume~1\control\my_dir'); or

>> addpath c:\docume~1\control\my_dir'; To remove specified directory from the MATLAB search path, use the command rmpath . Learn more about MATLAB search path through online help.

Type simply the name of the file decayed_sin to execute it from the command window. Script can also be saved and executed simultaneously by clicking the icon in the main toolbar.

To open the existing M-file from the MATLAB command window, type edit filename (or follow File Open option from the main menu bar or click on icon in the main toolbar).

All variables created during the runtime of the script file are left in the workspace. Using who or whos , you can get information about them, and also access them by workspace window.

Exercise M1.10 Modify the script file written in Fig. M1.20 in the following way: 1. An error message should prompt, if final time is less than initial time 2. In addition to initial and final time, and time constant, the program should prompt the user to enter the amplitude of the sine wave. 3. It should plot the Yt curve; however, wherever Yt crosses the zero-axes, an indication through x -mark should appear. 4. Display current date and time at the end. (Hint: Learn commands date and clock using online help). 5. Calculate the total execution time of the program. (Hint: Learn tic and toc commands).

Exercise M1.11Learn more about 1) For loops, 2) While Loops, and 3) If-Else-End constructions using online help.

Fig. M1.19 Example M-file

Developing user-defined Functions

Suppose you want to write a function to generate and plot N data points of the exponentially-decaying sinusoid of amplitude A, frequency f, and exponential time-constant . A MATLAB function which can take all these parameters as arguments and provide decaying sinusoid as an output is shown in Fig. M1.20.

Generate an M-file with the code given in Fig.M1.20. When you attempt to save the file, editor will automatically assign a function name decaying_sin to your M-file. Save the function to the current working directory or include your personal directory into MATLAB search path by using addpath command. We must avoid duplicating function names with built-in MATLAB functions or keywords.

A function file begins with a function definition line, which contains the keyword function, a well-defined list of input and output arguments, and function name. Some examples of function definition are given below (execute help function for details):

function [ph, mag] = complex (z) function [r,theta] = polar_form(a, b) function decaying_sin( ) function sys_response( ) The first commented line just after the function definition is called the H1 line. This line is automatically catalogued in the contents.m file of the directory in which function file resides. This allows the line to be searched by the lookfor command. Very carefully chosen keywords related to your function should come in the H1 line. Note that if there is any blank space before the % sign in the H1 line, then it is no longer H1 line !!

All comment lines immediately following the function definition line and immediately before the first executable statement of the function are displayed by MATLAB if help is asked on the function. Type

>> help decaying_sin and see what MATLAB displays.

Input-argument names used in the function are local to the function; so arbitrary variable names can be used to call the function. The name of another function can also be passed as an input variable. The following are examples of legal function calls:

Fig. M1.20 DECAYING_SIN Function

>> Yt = decaying_sin (time_span, time_const, mag, freq, pts)In this case, input variables time_span, time_const, mag, freq, and pts must be defined before the function call.>> res = decaying_sin ([0 10], tau, 3, 50, 1000)Here the input variable tau must be defined beforehand; all other inputs have been defined in the function call.>> sig = decaying_sin ([0,10], 2, 3, 50, 100)Here all the inputs have been specified in the call statement.>> decaying_sin ([0,10], 3, 0.5, 60, 100) In this case, the output is assigned to generic variable ans.

Exercise M1.12

1. Execute decaying_sin function with less than four and greater than five arbitrary arguments and interpret the messages. Study nargin and nargout commands through online help.

2. Execute decaying_sin function with tspan = [-1 10] and tspan=[3 0] and interpret the messages.

3. Execute the function as Yt = decaying_sin([0 5], 3, 0.5, 50). What is the length of the vector Yt ?

4. In some applications we don't want to generate the plot every time. We may need only output given by the function. Modify the above function with one more input argument str' to provide control over whether we want to generate the plot or not? If str = Y' or y', then it should generate the plot. If str = N' or n', then it should not. If any other character is passed, then it should give the error message Unrecognized user input' and terminate the program. You also need to modify processing with the nargin command.

Exercise M1.13 Write a function named specifications with the following input and output arguments:

Input arguments:

1. vector tspan of initial and final times.

2. Scalars y0 0, zeta , wn, and theta.

3. Character argument str controlling whether to plot the final result or not.

4. Scalar N of number of data points required to be generated.

Output arguments:

1. Yt calculated by 2. Tau calculated by 3. Tr calculated by 4. Tp calculated by 5. Mp calculated by

MATLAB MODULE 2

Control System Toolbox and Symbolic Math Toolbox

Control System Toolbox

Control System Toolbox is a collection of commands to be used for control systems' analysis and design. We will be using only some of these commands, because of the limited nature of course profile. Description of these commands will be distributed in different modules.

In this module, we will present commands related to transfer functions and system responses. To see all the commands in the Control System Toolbox and their functionalities, type help control in the MATLAB command window. MATLAB will respond with

>> help control

Control System Toolbox Version 6.0 (R14) 05-May-2004 General. ctrlpref - Set Control System Toolbox preferences. ltimodels - Detailed help on the various types of LTI models. ltiprops - Detailed help on available LTI model properties.

Creating linear models.tf - Create transfer function models. zpk - Create zero/pole/gain models. ss, dss - Create state-space models. frd - Create a frequency response data models.filt - Specify a digital filter. lti/set - Set/modify properties of LTI models.

Data extraction. tfdata - Extract numerator(s) and denominator(s). zpkdata - Extract zero/pole/gain data. ssdata - Extract state-space matrices. dssdata - Descriptor version of SSDATA.frdata - Extract frequency response data. lti/get - Access values of LTI model properties.

Conversions. tf - Conversion to transfer function. zpk - Conversion to zero/pole/gain. ss - Conversion to state space. frd - Conversion to frequency data. chgunits - Change units of FRD model frequency points. c2d - Continuous to discrete conversion. d2c - Discrete to continuous conversion. d2d - Resample discrete-time model.

System interconnections. append - Group LTI systems by appending inputs and outputs. parallel - Generalized parallel connection (see also overloaded +). series - Generalized series connection (see also overloaded *). feedback - Feedback connection of two systems. lft - Generalized feedback interconnection (Redheffer star product). connect - Derive state-space model from block diagram description.

System gain and dynamics. dcgain - D.C. (low frequency) gain. bandwidth - System bandwidth. lti/norm - Norms of LTI systems. pole, eig - System poles. zero - System (transmission) zeros. pzmap - Pole-zero map. iopzmap - Input/output pole-zero map. damp - Natural frequency and damping of system poles. esort - Sort continuous poles by real part. dsort - Sort discrete poles by magnitude. stabsep - Stable/unstable decomposition. modsep - Region-based modal decomposition.

Time-domain analysis. ltiview - Response analysis GUI (LTI Viewer). step - Step response. impulse - Impulse response. initial - Response of state-space system with given initial state.lsim - Response to arbitrary inputs. gensig - Generate input signal for LSIM. covar - Covariance of response to white noise.

Frequency-domain analysis.

ltiview - Response analysis GUI (LTI Viewer). bode - Bode diagrams of the frequency response. bodemag - Bode magnitude diagram only. sigma - Singular value frequency plot. nyquist - Nyquist plot. nichols - Nichols plot. margin - Gain and phase margins. allmargin - All crossover frequencies and related gain/phase margins. freqresp - Frequency response over a frequency grid. evalfr - Evaluate frequency response at given frequency. frd/interp - Interpolates frequency response data.

Classical design. sisotool - SISO design GUI (root locus and loop shaping techniques). rlocus - Evans root locus.

Pole placement.place - MIMO pole placement. acker - SISO pole placement. estim - Form estimator given estimator gain. reg - Form regulator given state-feedback and estimator gains.

LQR/LQG design. lqr, dlqr - Linear-quadratic (LQ) state-feedback regulator. lqry - LQ regulator with output weighting. lqrd - Discrete LQ regulator for continuous plant.

kalman - Kalman estimator. kalmd - Discrete Kalman estimator for continuous plant. lqgreg - Form LQG regulator given LQ gain and Kalman estimator. augstate - Augment output by appending states.

State-space models. rss, drss - Random stable state-space models. ss2ss - State coordinate transformation. canon - State-space canonical forms. ctrb - Controllability matrix. obsv - Observability matrix. gram - Controllability and observability gramians. ssbal - Diagonal balancing of state-space realizations. balreal - Gramian-based input/output balancing. modred - Model state reduction.minreal - Minimal realization and pole/zero cancellation. sminreal - Structurally minimal realization.

Time delays.hasdelay - True for models with time delays.totaldelay - Total delay between each input/output pair.delay2z - Replace delays by poles at z=0 or FRD phase shift.pade - Pade approximation of time delays.

Model dimensions and characteristics.class - Model type ('tf', 'zpk', 'ss', or 'frd').size - Model sizes and order.lti/ndims - Number of dimensions. lti/isempty - True for empty models. isct - True for continuous-time models. isdt - True for discrete-time models. isproper - True for proper models. issiso - True for single-input/single-output models. reshape - Reshape array of linear models.

Overloaded arithmetic operations. + and - - Add and subtract systems (parallel connection). * - Multiply systems (series connection). \ - Left divide -- sys1\sys2 means inv(sys1)*sys2. / - Right divide -- sys1/sys2 means sys1*inv(sys2). ^ - Powers of a given system. ' - Pertransposition. .' - Transposition of input/output map. [..] - Concatenate models along inputs or outputs. stack - Stack models/arrays along some array dimension. lti/inv - Inverse of an LTI system. conj - Complex conjugation of model coefficients.

Matrix equation solvers. lyap, dlyap - Solve Lyapunov equations. lyapchol, dlyapchol - Square-root Lyapunov solvers. care, dare - Solve algebraic Riccati equations. gcare, gdare - Generalized Riccati solvers. bdschur - Block diagonalization of a square matrix.

Demonstrations.Type "demo" or "help ctrldemos" for a list of available demos. control is both a directory and a function. --- help for modeldev/control.m ---

MODELDEV/CONTROL In this module, we will learn how to represent transfer functions in the MATLAB, partial fraction expansion of rational expressions, representation of transfer functions as LTI objects, and to obtain time domain responses of LTI systems. Important commands for this module are:

roots Find polynomial roots poly Convert roots to polynomial polyval Evaluate polynomial value conv Convolution and polynomial multiplication deconv Deconvolution and polynomial division residue Partial-fraction expansion (residues) tf Creation of transfer functions or conversion to transfer functions pole Compute the poles of LTI models zero Transmission zeros of LTI systems tfdada Quick access to transfer function data zpkdata Quick access to zero-pole-gain data pzmap Pole-zero map of LTI models zpk Create zero-pole-gain models or convert to zero-pole-gain format step Step response of LTI models impulse Impulse response of LTI models lsim Simulate time response of LTI models to arbitrary inputs gensig Periodic signal generator for time response simulations with lsim

Polynomials

Consider a polynomial s 3 +3 s 2 +4', to which we attach the variable name p. MATLAB can interpret a vector of length n +1 as the coefficients of an n th -order polynomial. Coefficients of the polynomial are interpreted in descending powers. Thus, if the polynomial is missing any coefficient, we must enter zeros in the appropriate places in the vector. For example, polynomial p can be represented by the vector [1 3 0 4] in MATLAB. For example:

>> p=[1 3 0 4] p = 1 3 0 4Roots of the polynomial can be obtained by roots command.

>> r=roots(p) r = -3.3553 0.1777 + 1.0773i 0.1777 - 1.0773i Given roots of a polynomial in a vector, a vector of polynomial coefficients can be obtained by the command poly.

>> p=poly(r) p = 1.0000 3.0000 0.0000 4.0000

Use the command polyval(p, s) to evaluate the polynomial represented by vector p at arbitrary value of s. For example, to evaluate the polynomial 's 3 +3 s 2 +4' at , type

>> polyval(p,sqrt(2)) ans = 12.8284

The product of two polynomials is found by taking the convolution of their coefficients. The function conv will do this for us. Consider an example of multiplying polynomial s 3 +3 s 2 +4' with s +2':

>> p1=[1 3 4]; >> p2=[1 2]; >> p3=conv(p1,p2) p3 = 1 5 10 8 The function deconv divides two polynomials and returns quotient as well as the remainder polynomial.

>> [q,r]=deconv(p1,p2) q = 1 1 r = 0 0 2 where q is the quotient and r is the remainder polynomial.

Exercise M2.1 Verify the deconvolution result given in vectors q and r.

Hint: Check whether p1 = conv(q,p2) + r or not?

Exercise M2.2 Let and . Obtain .

Consider the rational fractions of the form:

where the coefficients and are real constants, and and are integers.A fraction of the form G(s) can be expanded into partial fractions. To do this, first of all we factorize the denominator polynomial D(s) into first-order factors. The roots of D(s) can be real or complex; distinct or repeated.

Let, vectors N and D specify the coefficients of numerator and denominator polynomials and respectively. The command [A,p,K]=residue(N,D) returns residues in column vector A, the roots of the denominator in column vector p, and the direct term in scalar K. If there are no multiple roots, the fraction can be represented as:

If there are roots of multiplicity mr , i.e. , , then the expansion includes terms of the form:

If , K is empty (zero).

Supplying 3 arguments A, p, and K to residue converts the partial fraction expansion back to the polynomial with coefficients in N and D. Consider the rational fraction:

MATLAB solution to partial fraction problem can be given by:

>> N=[10 40]; >> D=[1 4 3 0]; >> [A,p,K]=residue(N,D) A = 1.6667 -15.0000 13.3333 p = -3 -1 0 K = [ ]

Example M2.1 Consider the function

The following MATLAB session evaluates the residues.

>> N = 13; >> D = [1 6 22 30 13 0]; >> [A,p,K]=residue(N,D) A = 0.0200 - 0.0567i 0.0200 + 0.0567i -1.0400 -1.3000 1.0000 p = -2.0000 + 3.0000i -2.0000 - 3.0000i -1.0000 -1.0000 0 K = [ ] Exercise M2.3 Represent the matrices A, p, and K obtained in Example M2.1 in partial fraction form and convert back to the polynomial form. Counter check your answer with MATLAB.

Exercise M2.4 Consider the rational fraction:

Obtain partial fraction form in terms of K. Solve using MATLAB for and countercheck your answer.

Exercise M2.5 Consider the rational fraction: .

Identify the points where:

1. and

2. Note: The roots of the numerator polynomial, i.e. , , are known as the zeros of and the roots of the denominator polynomial, i.e. , , are known as the poles of

Transfer Functions Transfer functions can be represented in MATLAB as LTI (Linear Time Invariant) objects using numerator and denominator polynomials. Consider the transfer function given by It can be represented in MATLAB as:

>> num = [1 1]; >> den = [1 3 1]; >> G = tf(num,den) Transfer function: ..s + 1----------------- s^2 + 3 s + 1

Example M2.2 The function conv has been used to multiply polynomials in the following MATLAB session for the transfer function

>> n1 = [5 1]; >> n2 = [15 1]; >> d1 = [1 0]; >> d2 = [3 1]; >> d3 = [10 1]; >> num = 100*conv(n1,n2); >> den = conv(d1,conv(d2,d3)); >> GH = tf(num,den)

Transfer function: 7500 s^2 + 2000 s + 100-----------------------------------....30 s^3 + 13 s^2 + s To learn more about LTI objects given by tf, type ltimodels tf in MATLAB command window. Type ltiprops tf on MATLAB prompt to learn the properties associated with an LTI object represented by tf.

Transfer functions can also be entered directly in polynomial form as we enter them in the notebook using LTI objects. For example, observe the following MATLAB session.

>> s=tf('s') %Define 's' as an LTI object in polynomial formTransfer function: s>> G1=150*(s^2+2*s+7)/[s*(s^2+5*s+4)] % Form G1(s) as an LTI transfer function % in polynomial form.Transfer function: 150 s^2 + 300 s + 1050---------------------------------......s^3 + 5 s^2 + 4s

>> G2=20*(s+2)*(s+4)/[(s+7)*(s+8)*(s+9)] % Form G2(s) as an LTI transfer % function in polynomial form.Transfer function: .....20 s^2 +120 s + 160------------------------------------s^3 + 24 s^2 + 191s + 504 The commands pole and zero calculate the poles and zeros of LTI models.

>> pole(G1) ans = 0 -4 -1 >> zero(G1) ans = -1.0000 + 2.4495i -1.0000 - 2.4495iTo extract numerator and denominator polynomials, use the function tfdata .>> [num,den]=tfdata(G,'v') num = 0 1 1 den = 1 3 1To extract zeros and poles of transfer function simultaneously, use the function zpkdata .

>> [z,p]=zpkdata(G,'v') z = -1 p = -2.6180 -0.3820 If we know zeros and poles of the system with gain constant, the transfer function of LTI system can be constructed by zpk command. For example, to create a unity gain transfer function G3(s) with zero at -1 and two poles at -2.618 and -0.382, follow the MATLAB session given below.

>> G3=zpk(-1,[-2.618 -0.382],1)Zero/pole/gain: (s+1) --------------------------- (s+2.618)(s+0.382) The polynomial transfer function created with tf can be converted to zero-pole-gain model by the command zpk and vice versa . The following MATLAB session gives the zero-pole-gain format of LTI system represented by G(s).

>> zpk(G)Zero/pole/gain: (s+1)--------------------------- (s+2.618)(s+0.382) To observe the polynomial form of the transfer function G3(s), enter

>> tf(G3)Transfer function: s+1---------------------- s^2 + 3s +1 To learn more about LTI objects given by zpk, type ltimodels zpk in MATLAB command window. Type ltiprops zpk on MATLAB prompt to learn the properties associated with an LTI object represented by zpk.

The function pzmap(G) plots the poles and zeros of the transfer function G(s) on complex plane. When used with two left hand side arguments, [p,z] = pzmap(G), the function returns the poles and zeros of the system in two column vectors p and z. For example:

>> [p,z]=pzmap(G) p = -2.6180 -0.3820 z =

-1

System Response

Step and impulse responses of LTI objects can be obtained by the commands step and impulse . For example, to obtain the step response of the system represented in LTI object G, enter

>> step(G)The MATLAB response to this command is shown in Fig. M2.1.

Fig. M2.1To obtain the impulse response, enter

>> impulse(G)The MATLAB response to this command is shown in Fig. M2.2.

Fig. M2.2

Step and impulse response data can be collected into MATLAB variables by using two left hand arguments. For example, the following commands will collect step and impulse response amplitudes in yt and time samples in t.

[yt, t] = step(G) [yt, t] = impulse(G)Response of LTI systems to arbitrary inputs can be obtained by the command lsim. The command lsim(G,u,t) plots the time response of the LTI model G to the input signal described by u and t. The time vector t consists of regularly spaced time samples and u is a matrix with as many columns as inputs and whose ith -row specifies the input value at time t(i). Observe the following MATLAB session to obtain the time response of LTI system G to sinusoidal input of unity magnitude.

>> t=0:0.01:7; >> u=sin(t); >> lsim(G,u,t)The response is shown in Fig. M2.3.

Fig. M2.3

Exercise M2.6 i. Obtain the response of to ramp and parabolic inputs using lsim command.

ii. Obtain the response of to ramp and parabolic inputs using step command.

The function gensig generates periodic signals for time response simulation with lsim function. It can generate sine, square, and periodic pulses. All generated signals have unit amplitude. Observe the following MATLAB session to simulate G ( s ) for 20 seconds with a sine wave of period 5 seconds.

>> [u,t]=gensig( 'sin' ,5,20); %Sine wave with period 5 sec and duration 20 sec >> lsim(G,u,t) %Simulate G(s) with u and t.The response is shown in Fig. M2.4.

Fig. M2.4

Exercise M2.7 Generate square and pulse signals with the period of 4 seconds and obtain time response of for a duration of 30 seconds.

Example M2.3 The following MATLAB script calculates the step response of second-order system

with and various values of t=[0:0.1:12]; num=[1]; zeta1=0.1; den1=[1 2*zeta1 1]; zeta2=0.2; den2=[1 2*zeta2 1]; zeta3=0.4; den3=[1 2*zeta3 1]; zeta4=0.7; den4=[1 2*zeta4 1]; zeta5=1.0; den5=[1 2*zeta5 1]; zeta6=2.0; den6=[1 2*zeta6 1]; [y1,x]=step(num,den1,t); [y2,x]=step(num,den2,t); [y3,x]=step(num,den3,t); [y4,x]=step(num,den4,t); [y5,x]=step(num,den5,t); [y6,x]=step(num,den6,t); plot(t,y1,t,y2,t,y3,t,y4,t,y5,t,y6) xlabel( 't' ), ylabel( 'y(t)' ) grid Response through the above MATLAB script is shown in Fig M2.5.

Fig. M2.5

The following MATLAB script calculates the impulse response of second-order system

with and various values of t=[0:0.1:10]; num=[1]; zeta1=0.1; den1=[1 2*zeta1 1]; zeta2=0.25; den2=[1 2*zeta2 1]; zeta3=0.5; den3=[1 2*zeta3 1]; zeta4=1.0; den4=[1 2*zeta4 1]; [y1,x,t]=impulse(num,den1,t); [y2,x,t]=impulse(num,den2,t); [y3,x,t]=impulse(num,den3,t); [y4,x,t]=impulse(num,den4,t); plot(t,y1,t,y2,t,y3,t,y4) xlabel( 't' ), ylabel( 'y(t)' ) grid Response through the above MATLAB script is shown in Fig M2.6.

Fig. M2.6

Right-clicking away from the curves obtained by step, impulse, and lsim commands brings up a menu. From this menu, various time-response characteristics can be obtained and plotted on the graph ( Discussion on time-response characteristics will appear later in Module 5).

Symbolic Math Toolbox

MATLAB's Symbolic Math (Symbolic Math ematics) toolbox allows users to perform symbolic mathematical computations using MATLAB. The only basic requirement is to declare symbolic variables before they are used. For control systems analysis and design, symbolic math toolbox is particularly important because of the following: 1. Transfer functions and other expressions can be entered in symbolic form as we write them in the notebook. 2. Symbolic expressions can be manipulated algebraically and simplified. 3. It is straightforward to convert symbolic polynomials to the vectors of corresponding power-term coefficients. 4. Expressions can be pretty printed' for clarity in the MATLAB command window.Type help symbolic on the MATLAB command prompt to see all the functionalities available with Symbolic Math toolbox. In this section, we will learn commands of Symbolic Math toolbox particularly useful for control engineering.First we demonstrate the power of Symbolic Math toolbox by calculating inverse Laplace transform. The following MATLAB session gives the steps performed during the calculation of inverse Laplace transform of using Symbolic Math.

Exercise M2.8 Initialize s and T as symbols. Using Symbolic Math tools, find the response of the first- order system ,with the step excitation of strength A .

Hint: Find the inverse Laplace transform of .

Exercise M2.9 Find manually the Laplace transform of . Using Symbolic Math tools, declare t as symbolic variable and countercheck your result. Use the function laplace(g) to calculate the Laplace transform.

The function simple(G) finds simplest form of G(s) with the least number of terms. simplify(G) can be used to combine partial fractions. Symbolic Math toolbox also contains other commands that can change the look of the displayed result for readability and form. Some of these commands are: collect(G) - collects common-coefficient terms of G(s); expand(G) - expands product of factors of G(s); factor(G)-factors G(s); vpa(G, places) - stands for variable precision arithmetic (this command converts fractional symbolic terms into decimal terms with a specified number of decimal places).Consider the function . MATLAB response to the simplification of using the function simplify is shown below.

>> syms s

>> G = (1/s)+(1/3)*(1/(s+4))-(4/3)*(1/(s+1))G =1/s+1/3/(s+4)-4/3/(s+1) >> pretty(G)

...................1 ....................11/s + 1/3 ------- ...- 4/3...-------................s + 4...............s + 1 >> pretty(simplify(G))

.............4--------------------s (s + 4) (s + 1)In the above example, the symbolic fractions 1/3 and 4/3 will be converted to 0.333 and 1.33 if the argument places in vap(G, places) is set to 3.>> pretty(vpa(G,3))............0.333 ....1.331/s + ---------- - ----------........... s + 4. ....s + 1.

Exercise M2.10 Consider the function . Show using Symbolic Math tools that the simplified form of its Laplace transform is .

Basic mathematical operators +, , , and are applicable to symbolic objects also. For example, simplification of the closed-loop system with forward gain forward-path transfer function , and feedback-path transfer function , is given by . This can be done using Symbolic Math toolbox as follows

>> syms s K; >> G = 2.5/(s*(s+5)); >> H = 1/(0.1*s+1); >> M = K*G/(1+G*H)M =5/2*K/s/(s+5)/(1+5/2/s/(s+5)/(1/10*s+1)) >> pretty(M)

K5/2 ------------------------------------------ / 1 \ s (s + 5)| 1 + 5/2 ---------------------- |

\ s (s + 5) (1/10 s + 1) / >> pretty(simplify(M)) (s + 10) K5/2 ------------------------- 3 2 s + 15 s + 50 s + 25

With Symbolic Math toolbox, symbolic transfer functions can easily be converted to the LTI (Linear Time-Invariant) transfer function objects. This conversion is done in two steps. The first step uses the command numden to extract the symbolic numerator and denominator of G (s). The second step converts, separately, the numerator and denominator to vectors using the command sym2poly . The last step consists of forming the LTI transfer function object by using the vector representation of the transfer function's numerator and denominator. The command sym2poly doesn't work on symbolic expressions with more than one variable. As an example, we form the LTI object from obtained in the above example with .

The command poly2sym converts polynomial coefficient vectors to symbolic polynomial. Learn more about poly2sym using online help.MATLAB MODULE 3

Simulink

Objectives: Building simple Simulink simulations.

Running Simulink simulation to predict a system's behaviour.

The MATLAB Control System Toolbox offers functions for finding the transfer functions from a given block diagram. However, as we shall shortly see, the simulation environment provided by MATLABs Simulink Toolkit obviates the need for block diagram reduction. The Simulink model mimics the block diagram of a feedback control system and is used to evaluate the response of controlled variable to any test input. It also provides the response of any internal variable of the control system (output variable of a subsystem block) without the need for block diagram reduction.Let us reiterate the fact we have emphasized earlier: a good plant/process model is the backbone of any realistic control design. A Simulink model based on the structure and parameters of the system model is constructed. The responses of the actual system and its Simulink model are obtained using a set of test inputs. If the actual responses to the test inputs were significantly different from the Simulink responses, certain model parameters would have to be revised, and/or the model structure would have to be refined to better reflect the actual system behaviour. Once satisfactory model performance has been achieved, various control schemes can be designed and implemented.In practice, it is best to test a control scheme off-line by evaluating the system performance in the safety of the Simulink environment. The key components of a control system include actuators, sensors, and the plant/process itself. A decision to include all aspects such as amplifier saturation, friction in the motor, backlash in gears, dynamics of all the devices, etc., may improve the model, but the complexity of the model may result in a more complicated controller design, which will ultimately increase the cost and sophistication of the system. The design is usually carried out using an approximated model; the evaluation of the design is done on the true model, which includes nonlinearities, and other aspects neglected in the approximate model. Simulink is an excellent tool for this evaluation. SIMULINK (SIMUlation LINK) is an extension of MATLAB for modeling, simulating, and analyzing dynamic, linear/nonlinear, complex control systems. Graphical User Interface (GUI) and visual representation of simulation process by simulation block diagrams are two key features which make SIMULINK one of the most successful software packages, particularly suitable for control system design and analysis.Simulation block diagrams are nothing but the same block diagrams we are using to describe control system structures and signal flow graphs. SIMULINK offers a large variety of ready-to-use building blocks to build the mathematical models and system structures in terms of block diagrams. Block parameters should be supplied by the user. Once the system structure is defined, some additional simulation parameters must also be set to govern how the numerical computation will be carried out and how the output data will be displayed.Because SIMULINK is graphical and interactive, we encourage you to jump right in and try it. To help you start using SIMULINK quickly, we describe here the simulation process through a demonstration example with MATLAB version 7.0, SIMULINK version 6.0.To start SIMULINK, enter simulink command at the MATLAB prompt. Alternatively one can also click on SIMULINK icon shown in Fig. M3.1.

Fig. M3.1 MATLAB Desktop main menu and SIMULINK icon

A SIMULINK Library Browser (Fig. M3.2) appears which displays tree-structured view of the SIMULINK block libraries. It contains several nodes; each of these nodes represents a library of subsystem blocks that is used to construct simulation block diagrams. You can expand/collapse the tree by clicking on the boxes beside each node and block in the block set pan.

Fig. M3.2 SIMULINK Library Browser

Expand the node labeled Simulink. Subnodes of this node ( Commonly Used Blocks, Continuous, Discontinuities, Discrete, Logic and Bit Operations, etc) are displayed. Now for example, expanding the Sources subnode displays a long list of Sources library blocks. Simply click on any block to learn about its functionality in the description box (see Fig. M3.3).

Fig. M3.3 Blocks in Sources subnode

You may now collapse the Sources subnode, and expand the Sinks subnode. A list of Sinks library block appears (Fig.M3.4). Learn the purpose of various blocks in Sinks subnode by clicking on the blocks.

Fig. M3.4 Blocks in Sinks subnode

Exercise M3.1 Expand the Continuous, Discontinuities, Discrete, and Math Operations subnodes. Study the purpose of various blocks in these subnodes in description box.

We have described some of the subsystem libraries available that contain the basic building blocks of simulation diagrams. The reader is encouraged to explore the other libraries as well. You can also customize and create your own blocks. For information on creating your own blocks, see the MATLAB documentation on Writing S- Functions.We are now ready to proceed to the next step, which is the construction of a simulation diagram. In the SIMULINK library browser, follow File New Model or hit Ctrl+N to open an untitled' workspace (Fig.M3.5) to build up an interconnection of SIMULINK blocks from the subsystem libraries.

Fig. M3.5 Untitled workspace

Let us take a simple example. The block diagram of a dc motor (armature-controlled) system is shown in Fig. M3.6

Fig. M3.6 Block diagram of a dc motor (armature-controlled) system where

is the resistance of the motor armature (ohms) = 1.75

is the inductance of the motor armature (H) = 2.83

INCLUDEPICTURE "http://nptel.iitm.ac.in/courses/Webcourse-contents/IIT-Delhi/Control%20system%20design%20n%20principles/matlab/module3/module3intro_middle_image008.gif" \* MERGEFORMATINET is the torque constant (Nm/A) = 0.0924

is the back emf constant (V sec/rad) = 0.0924

is the inertia seen by the motor (includes inertia of the load) (kg-m2 ) = is the mechanical damping coefficient associated with rotation (Nm/(rad/sec))= 5.0

INCLUDEPICTURE "http://nptel.iitm.ac.in/courses/Webcourse-contents/IIT-Delhi/Control%20system%20design%20n%20principles/matlab/module3/module3intro_middle_image022.gif" \* MERGEFORMATINET is the applied voltage (volts) = 5 volts

We will implement the model shown in Fig. M3.6 in the untitled work space (Fig. M3.5).

Let us first identify the SIMULINK blocks required to implement the block diagram of Fig. M3.6. This is given in Fig. M3.7.

Fig. M3.7 SIMULINK blocks required for implementation

Identifying the block(s) required for simulation purpose is in fact the first step of the construction of simulation diagram in SIMULINK. The next step is to drag and drop the required blocks from SIMULINK block libraries to untitled workspace. Let us put the very first block for applied voltage (Ea) to workspace.Expand the Sources subnode, move the pointer and click the block labeled Constant, and while keeping the mouse button pressed down, drag the block and drop it inside the Simulation Window; then release the mouse button (Fig. M3.8).Right clicking on the block will provide various options to users from which one can cut, copy, delete, format (submenu provides facilities for rotation of the block, flipping, changing the font of block name,...), etc... Exercise M3.2 Drag and drop all the blocks we have identified (Fig. M3.7) from the Library Browser to the untitled Workspace and place them as shown in Fig. M3.9.

Fig. M3.8 Drag and drop blocks to Workspace from Library Browser

Fig. M3.9 Unconnected blocks in Workspace It is visible that all the block parameters are in their default settings. For example, the default transfer function of Transfer Fcn block is and default signs of Sum block are + +. We need to configure these block parameters to meet our modeling requirements. It is straightforward. Double click the block to set up its parameters. For example, double clicking the Transfer Fcn block opens the window titled Block Parameters: Transfer Fcn, shown in Fig. M3.10.

Fig. M3.10 Transfer function block parameters window

For armature circuit transfer function, no need to change the numerator parameter. For denominator parameters, enter for , which will be interpreted by SIMULINK as .

To enhance the interpretability of simulation diagram, we can also change the block identification name. Simply click on the text Transfer Fcn to activate the small window around the text to change the block name. For our simulation block diagram, the suitable text for Transfer Fcn block may be Armature circuit. Before we move to the last step of interconnecting the blocks as per the desired structure, just finish Exercise M3.3. Note that the Decimation parameter value by default is 1. Increasing this value reduces the number of data samples taken over the simulation time. We have used the default value of 1.

Exercise M3.3 Modify all the block parameters as per system parameters given for Fig. M3.7, and give appropriate names to the blocks.

Lines are drawn to interconnect these blocks as per the desired structure. A line can connect output port of one block to the input port of another block. A line can also connect the output port of one block with input ports of many blocks by using branch lines. We suggest readers to perform the following line/block operations on blocks dragged in workspace to get hands on practice.

To connect the output port of one block to the input port of another block:

1. Position the pointer on the first block's output port; note that the cursor shape changes to cross hair.

2. Press and hold down the left mouse button.

3. Drag the pointer to second block's input port.

4. Position the pointer on or near the port; the pointer changes to a double cross hair.

5. Release the mouse button. SIMULINK replaces the port symbol by a connecting line with an arrow showing the direction of signal flow.

Another simple methodology doesn't require dragging the line. Block1 output port is required to be connected to Block2 input port.

1. select Block1 by clicking anywhere inside the block.

2. Hold down the Ctrl key.

3. Click on block2; both the blocks will be connected.

To connect the output port of one block with the input ports of several blocks, we can use branch lines. Both the existing line and the branch line carry the same signal. To add a branch line, do the following:

1. Position the pointer on the line where you want the branch line to start.

2. While holding down the Ctrl key, left click on the line segment; note that the cursor shape changes to cross hair.

3. Release the control key, while pressing down the left mouse button; drag the pointer to the input port of the target block.

4. Release the mouse button; target block will be connected to the line segment.

Some of the important line-segment and block operations are as follows:

1. To move a line segment, position the pointer on the segment you want to move. Press and hold down the left mouse button. Drag the pointer to the desired location and release. Note that this operation is valid with line segments only, not with the dedicated connecting lines between two blocks.

2. To disconnect a block from its connecting lines, hold down the shift key, then drag the block to a new location. Incoming and outgoing lines will be converted to red colored dotted lines. One can insert a different block between these lines.

Exercise M3.4 Connect all the blocks appropriately as per the block diagram given in Fig. M3.7. Make use of the block interconnection points discussed above.

Now let us give a name to the untitled workspace. Hit Ctrl + S to save the developed simulation diagram to the disk with an appropriate name. The file will be saved with the extension .mdl , an abbreviation for the model'.

We save the file using the name armature_dcmotor.mdl; the complete simulation diagram is shown in Fig. M3.11.

Finally, we need to set the parameters for the simulation run. Press Ctrl + E to open the simulation parameter configuration window. Left panel of the window (Fig. M3.12) displays a tree structured view of parameter submenu. In the Solver submenu, enter the start and stop time of the simulation (Fig. M3.13).

Fig. M3.11 Final simulation diagram ( download )

Fig. M3.12 Parameter configuration submenu

Fig. M3.13 Enter simulation time

Now we are ready to simulate our block diagram of armature-controlled dc motor. Press icon to start the simulation. Note that the icon changes to ; pressing this icon, one can stop the simulation before stop time. After simulation is done, double click the Scope block to display the angular velocity variation with time. Click the autoscale icon in the display window to scale the axes as per the variable ranges. Autoscaled scope display is shown in Fig. M3.14. With zoom facility, try zooming the portion of graph between 0.5 to 1 sec, and 20 to 25 unit angular velocity to identify the numerical value of angular velocity at 0.8 seconds.

Fig. M3.14 Scope display of angular velocity

Set y-axis limits by right-clicking the axis and choosing Axes Properties. In Y-min, enter the minimum value for the y-axis. In Y-max, enter the maximum value for the y-axis. In Title, enter the title of the plot. See Fig. M3.15.

Fig. M3.15 Scope axis properties editor

Click the icon shown on the icon bar of Fig. M3.14 to open scope parameter editor (Fig. M3.16). General parameters include Number of axes, Time range, Tick labels, and Sampling.

Click on the Data history button. If you want input-output data from this scope to be available to MATLAB workspace for further analysis, check the button Save data to workspace. In the box Variable name, enter the variable name for saving the data. By default it will save the data with variable name ScopeData. With the pop-down menu Format, select the format in which you want to save the data.

Three specific formats for saving the data are as follows:

1. Structure with time: Data will be saved in structured format with time steps. Type the following commands in your MATLAB prompt and observe the outputs.

Fig. M3.16 Scope parameter setting window

>> ScopeData ScopeData = time: [4663x1 double] signals: [1x1 struct] blockName: 'armature_dcmotor/Angular Velocity' Structures are used in MATLAB to store mixed mode data types, and individual fields of the structure can be accessed by dot ' operator. To see the information stored in the field signals, type:

>> ScopeData.signals ans = values: [4663x1 double] dimensions: 1 label: '' title: '' plotStyle: 0 It indicates that the field signals contains subfield values, which is of 4663 x 1 size vector containing the values of angular velocity. Try accessing the field time of ScopeData.

Exercise M3.5 Plot the angular velocity against time using the plot command. Give suitable title to the plot and labels to x and y axes. Hint: You need to plot ScopeData.signals.values against ScopeData.time.

2. Structure : This is the same as Structure with time; the only difference is that the time steps will not be saved.

Exercise M3.6 Run the simulation with scope data to be saved as Structure format. Verify that the time field of ScopeData structure is actually an empty matrix.

3. Array : Array format is simply a two column matrix with number of data points being equal to number of rows. The maximum number of data points limits to the number entered in the box Limit data points to last. In Fig. M3.16, the limit is 5000 data points.

Exercise M3.7 Run the simulation with scope data to be saved as Array format. Repeat Exercise M3.5 with saved data matrix.

We have used an example to show how to build the simulink diagram, how to enter data and carry out a simulation in the SIMULINK environment. The reader will agree that this is a very simple process.

Solving the following exercises will make the readers more confident in solving the control system design and analysis problems through SIMULINK.

Exercise M3.8 This problem requires some modification in the above considered armature-controlled d.c. motor SIMULINK example.

1. The angular position is obtained by integrating the angular velocity. Implement this in the model and display angular position in a different scope.

2. Remove the constant applied voltage block. Obtain the Step, Ramp, and Sinusoidal responses of the system.

3. Simulate a closed-loop position control system assuming a proportional controller of gain KP .

Hint: Add a reference input signal for angular position and add a summing block which calculates the error between the angular position reference and the measured angular position. Multiply this error by the gain KP and let this signal be the applied voltage Ea .

Exercise M3.9 Consider a dynamic system consisting of a single output , and two inputs r and w :

where

Model the system in SIMULINK.

For and both step signals, obtain the system output . Display the output on scope. Also, using a SIMULINK block, etch the output to the workspace.

Hint: To implement deadtime, use the block Transport delay from Continuous, and identify suitable block from Sinks library to fetch the variable directly to the workspace.

Exercise M3.10 Assign 0.5, , and to , respectively.

Simulate for 10 seconds.

Display plots for on scope, and also save to the MATLAB file Yt.mat.

Hint: Use Math Function, Add, Divide, and Trigonometric Function from Math Operations block libraries.

Exercise M3.11 This problem is to study the effects of Proportional (P), Proportional + Integral (PI), and Proportional + Derivative (PD) control schemes on the temperature control system. A temperature control system has the block diagram given in Fig.M3.17. The input signal is a voltage and represents the desired temperature Simulate the control system using SIMULINK and find the steady-state error of the system when is a unit-step function and (i) (ii) and (iii) .

Fig. M3.17 Hint: Use PID Controller block from Simulink Extras Additional Linear to implement the PID controller.

Exercise M3.12 The block diagram in Fig. M3.18 shows the effect of a simple on-off controller on second-order process with deadtime.

Fig. M3.18

Implement and test the model in SIMULINK for step inputs of 5.0 and 10.0. Display the control signal u( t ) and output the on separate scopes and also fetch both the signals with time information to MATLAB workspace. Using MATLAB plot function, plot the control signal and the output; both against time on single graph.

Hint: To implement on-off controller, use Relay from Discontinuous block library.

Exercise M3.13 Simulate the Van der Pol oscillator, described by the following nonlinear differential equation:,

where is the disturbance (forcing function) given by . Assign Hint: Rewrite the second-order Van der Pol differential equation as a system of coupled first-order differential equations. Let,

The SIMULINK block diagram is to be built using Signal Generator, Gain, Integrator, Add, and Scope. The output of Add block is . Integrating it once will lead you to and second integration will lead you to Double click the Integrator block to add the initial conditions .

MATLAB MODULE 4

Feedback System Simulation

Transfer Function Manipulation

Suppose we have developed mathematical models in the form of transfer functions for the plant, represented by G(s), and the controller, represented by D(s), and possibly many other system components such as sensors and actuators. Our objective is to interconnect these components to form block diagram representation of a feedback control system. MATLAB offers several functions to carry out block diagram manipulations.

Two methods are available:

1. Solution via series, parallel, and feedback commands:

series(G,D) for a cascade connection of G(s) and D(s); parallel(G1,G2) for a parallel connection of G1(s) and G2(s); feedback(G,H, sign) for a closed-loop connection with G(s) in the forward path and H(s) in the feedback path; and sign is -1 for negative feedback or +1 for positive feedback (the sign is optional for negative feedback); and cloop(G,sign) for a unity feedback system with G(s) in the forward path, and sign is -1 for negative feedback or +1 for positive feedback (the sign is optional for negative feedback).

2. Solution via algebraic operations:

G*D for a cascade connection of G(s) and D(s); G1+G2 for a parallel connection of G1(s) and G2(s); G/(1+G*H) for a closed-loop negative feedback connection with G(s) in the forward path and H(s) in the feedback path; and G/(1-G*H) for positive feedback systems.

System Response

The transfer function manipulations give us a transfer function model M(s) between command input R(s) and output Y(s); model Mw(s) between disturbance input W(s) and output Y(s); a model between command input R(s) and control U(s), etc. It is now easy to use some of the control analysis commands available from the Control System Toolbox. impulse(M) and step(M) commands represent common control analysis operations that we meet in this book. Also frequently used in the book are frequency-response plots.

Example M4.1Consider the block diagram in Fig. M4.1.

Fig. M4.1

For value of gain KA = 80, the following two MATLAB sessions evaluate the step responses with respect to reference input R(s) and disturbance signal W(s) for

>> %Step response with respect to R(s)

>> s = tf('s'); >> KA = 80; >> G1 = 5000/(s+1000); >> G2 = 1/(s*(s+20)); >> M = feedback(series(KA*G1,G2),1) >> step(M)The MATLAB responds with

Transfer function:.......................400000-------------------------------------------------- s^3 + 1020 s^2 + 20000 s + 400000

and step response plot shown in Fig. M4.2. The grid has been introduced in the plot by right clicking on the plot and selecting Grid option.

Fig. M4.2

>> %Step response with respect to W(s) >> s = tf('s'); >> KA = 80; >> G1 = 5000/(s+1000); >> G2 = 1/(s*(s+20)); >> Mw = (-1) * feedback(G2, KA*G1) >> step(Mw)MATLAB responds with

Transfer function: .......................-s - 1000 ---------------------------------------------------- s^3 + 1020 s^2 + 20000 s + 400000and step response plot shown in Fig. M4.3.

Fig. M4.3 Example M4.2 Let us examine the sensitivity of the feedback system represented by the transfer function

The system sensitivity to parameter K is

Figure M4.4 shows the magnitudes of and versus frequency for K = 0.25; generated using the following MATLAB script. Text arrows have been introduced in the plot by following Insert from the main menu and selecting the option Text Arrow.

Note that the sensitivity is small for lower frequencies, while the transfer function primarily passes low frequencies.

w = 0.1:0.1:10; M = abs(0.25./((j*w).^2+j*w+0.25)); SMK = abs((j*w .* (j*w + 1))./((j*w).^2 + j*w +0.25)); plot(w,M,'r',w,SMK,'b'); xlabel('Frequency (rad/sec)'); ylabel('Magnitude');

Fig. M4.4 Of course, the sensitivity S only represents robustness for small changes in gain K. If K changes from 1/4 within the range K = 1/16 to K = 1, the resulting range of step responses, generated by the following MATLAB script, is shown in Fig. M4.5. This system, with an expected wide range of K, may not be considered adequately robust. A robust system would be expected to yield essentially the same (within an agreed-upon variation) response to selected inputs.

s = tf('s'); S = (s*(s+1))/(s^2+s+0.25); M1 = 0.0625/(s^2+s+0.0625); M2 = 0.25/(s^2+s+0.25); M3 = 1/(s^2+s+1); step(M1); hold on; step(M2); step(M3);

Fig. M4.5

Simulink Simulation

Simulink simulation is an alternative to block diagram manipulation followed by time-response analysis. From the Simulink model of a control system, output y in response to command r, output y in response to disturbance w, control u in response to command r, and all other desired internal variables can be directly obtained.

Example M4.3 Control system design methods discussed in this course are based on the assumption of availability of linear time invariant (LTI) models for all the devices in the control loop.

Consider a speed control system. The actuator for the motor is a power amplifier. An amplifier gives a saturating behaviour if the error signal input to the amplifier exceeds linear range value.

MATLAB simulink is a powerful tool to simulate the effects of nonlinearities in a feedback loop. After carrying out a design using LTI models, we must test the design using simulation of the actual control system, which includes the nonlinearities of the devices in the feedback loop.

Figure M4.6 is the simulation diagram of a feedback control system: the amplifier gain is 100 and the transfer function of the motor is 0.2083/(s +1.71). We assume the amplifier of gain 100 saturates at +5 or -5volts. The result of the simulation is shown in Fig. M4.7.

The readers are encouraged to construct the simulink model using the procedure described in Module 3. All the parameter settings can be set/seen by double clicking on related blocks.

Time and Output response data have been transferred to workspace using To Workspace block from Sinks main block menu. Clock block is available in Sources main menu. These variables are stored in the structure Output and Time in the workspace, along with the information regarding simulink model name. For example,

>> Output Output = time: [ ] signals: [1x1 struct] blockName: 'M4_3/To workspace Output' >> Time Time = time: [ ] signals: [1x1 struct] blockName: 'M4_3/To workspace Time'To access output and time values, one needs to access Output.signals.values and Time.signals.values . The step response plot has been generated by the following MATLAB script.

>> plot(Time.signals.values,Output.signals.values) >> xlabel('Time (sec)'); >> ylabel('Output'); >> title('Step Response');

Fig. M4.7

Example M4.4 In this example, we simulate a temperature control system with measurement noise added to the feedback signal. The process transfer function is

The deadtime minutes. The measurement noise parameters we have used are: mean of 0, variance of 0.5, initial seed of 61233, and sample time of 0. The simulink inputs a step of 30 to the system (Fig. M4.8). Deadtime block in this figure is Transport Delay block from Continuous library, and Random Number block is from Sources library.

Fig. M4.8 ( download )

The data has been transferred to the workspace using To Workspace block. The step response, generated using the following MATLAB script is shown in Fig. M4.9.

>> plot(Time.signals.values,Y.signals.values); >> ylabel('Output (Y)'); >> xlabel('Time(min)'); >> title('Step Response');

Fig. M4.9The performance of the system with measurement noise removed, is shown in Fig. M4.10. To remove the effect of noise, simply disconnect the Random number block from the Sum block in the feedback path.

MATLAB MODULE 5

Time Response Characteristics and LTI Viewer

LTI ViewerThe LTI ( Linear Time Invariant) Viewer is an interactive graphical user interface (GUI) for analyzing the time and frequency responses of linear systems and comparing such systems. In particular, some of the graphs the LTI Viewer can create are step and impulse responses, Bode, Nyquist, Nichols, pole-zero plots, and responses with arbitrary inputs. In addition, the values of critical measurements on these plots can be displayed with a click of the mouse. Table 5.1 shows the critical measurements that are available for each plot.

Table 5.1 -Peak time or Peak frequency Settling time Rise time Steady state value Gain/phase margins; zero dB/1800 frequencies Pole-zero value

Step--

Impulse----

Bode----

Nyquist----

Nichols----

Pole-zero-----

Here we provide steps you may follow to use the LTI Viewer to plot time and frequency responses.1. Access the LTI Viewer: The LTI Viewer window, shown in Fig. M5.1, can be accessed by typing ltiview in the MATLAB Command Window or by executing this command in an M-file.

Fig. M5.1 LTI Viewer Window1. Create LTI transfer functions: Create LTI transfer functions for which you want to obtain responses. The transfer functions can be created in an M-file or in the MATLAB Command Window. Run the M-file or MATLAB Command Window statements to place the transfer function in the MATLAB workspace. All LTI objects in the MATLAB workspace can be exported to the LTI Viewer. The following MATLAB commands create the transfer function . >> s = tf('s'); >> G = 1/(s+1);1. Select LTI transfer functions for the LTI Viewer: Choose Import under the File menu in the LTI Viewer window and select all LTI objects whose responses you wish to display in the LTI Viewer sometime during your current session. Selecting G results in Fig. M5.3.

Fig. M5.2 Import System Data Window

1. Select the LTI objects for the next response plot: Right-click anywhere in the LTI Viewer plot area to produce a pop-up menu. Under Systems, select or deselect the objects whose plots you want or do not want to show in the LTI Viewer. More than one LTI transfer function may be selected.

1. Select the plot type: Right-click anywhere in the LTI Viewer plot area to produce a pop-up menu. Under Plot Types, select the type of plot you want to show in the LTI Viewer (Fig. M5.3).

Fig. M5.3

Example M5.1 Take a typical underdamped second-order transfer function and import it to the LTI viewer window.

1. Select the characteristics: Right-click anywhere in the LTI Viewer plot area to produce a pop-up menu. Under Characteristics, select the characteristics of the plot you want displayed. More than one characteristic may be selected. For each characteristic selected, a point will be placed on the plot at the appropriate location. The characteristics menu and the submenu are displayed in Fig. M5.4 obtained by importing a typical second-order transfer function.Note the difference in the definition of rise time employed in the LTI Viewer with respect to the one used in the text.

Fig. M5.4 LTI Viewer with step response plot and characteristics

1. Interact with the plot: Zoom In (Zoom Out): Select the Zoom In (Zoom Out) button (with the + () sign) on the tool bar. Hold the mouse button down and drag a rectangle on the plot over the area you want to enlarge (deluge), and release the mouse button.

Original View: Select Reset to Original View in the menu popped up by right-click to return to original view of your plot after zooming.

Grid: Select Grid in the right-click menu to on or off the grid. The right click menu will not work if any zoom button on the tool bar is selected.

Normalize: Select Normalize in the right-click menu to normalize all curves in view.

Characteristics: Read the values of the characteristics by placing the mouse on the characteristics point on the plot. Left-click the mouse to keep the values displayed (Fig. M5.5).

Properties: Select Properties in the right-click menu or double-click anywhere (except the curve) on the graph sheet to change the appearance of the graph. You can change the title, axes labels, and limits, font sizes and styles, colors, and response characteristics definitions.

Coordinates and curve: Left-click the mouse at any point on the plot to read the system identification and the coordinates (Fig. M5.5, shown by square block).

Add text and graphics: Under the File menu, choose Print to Figure. An additional figure with toolbar will open (Fig. M5.6).The toolbar of this figure has additional tools for adding text, arrows, lines, legends, and to rotate the figure.

Additional plot-edit capabilities: The Edit menu of the LTI Viewer and the figures created by selecting Print to Figure, offer a wide variety of controls over the plot presentation.

2. Viewer preferences: Choose Viewer Preferences in the Edit menu. LTI Viewer Preferences window (Fig. M5.7) will open. This allows users to set parameters such as units (Units), style of labels (Style), response characteristics definitions (Characteristics), and also provide a control over the time and frequency vector generation (Parameters).

Fig. M5.5 Coordinate values in step response curve

Fig. M5.6 LTI response with text and graphics editor toolbarTime Response Characteristics in MATLAB window

Example M5.1

Consider the position control system shown in Fig. M5.8.

.

(transfer function of motor, gears, and load)

(transfer function of power amplifier)

KA = preamplifier gain

sensitivity of input and output potentiometers

Time response characteristics of the system are generated by the following MATLAB script.

s = tf('s'); G1 = 100/(s+100); G2 = 0.2083/(s*(s+1.71)); K = 1000; G = series(K*G1,G2); H = 1/pi; M = series(feedback(G,H),H); ltiview(M);MATLAB response is shown in Fig. M5.9.

In the following we compare the time response characteristics of this system with the one obtained by replacing the power amplifier with a transfer function of u