matlab module 1

Upload: mohammed-mansoor

Post on 07-Apr-2018

269 views

Category:

Documents


4 download

TRANSCRIPT

  • 8/4/2019 Matlab Module 1

    1/264

    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 Window2. Current Directory3. Workspace4. Command History

    A particular window can be activated by clicking anywhere inside its borders.

  • 8/4/2019 Matlab Module 1

    2/264

    Fig. M1.1 MATLAB Desktop (version 7.0, release 14)

    Desktop layout can be changed by following Desktop --> Desktop Layoutfrom the main menuas shown in Fig. M1.2 (Default option gives Fig. M1.1).

  • 8/4/2019 Matlab Module 1

    3/264

    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.

  • 8/4/2019 Matlab Module 1

    4/264

    Working with Command Windowallows 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, Tis 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.

  • 8/4/2019 Matlab Module 1

    5/264

    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 =

  • 8/4/2019 Matlab Module 1

    6/264

    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 Aand aaredifferent.

    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.

  • 8/4/2019 Matlab Module 1

    7/264

    Fig. M1.4 Command Window with example operations

  • 8/4/2019 Matlab Module 1

    8/264

    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 jhas not been assigned

    any prior local value.

    MATLAB representation of complex number :

    or

    or

  • 8/4/2019 Matlab Module 1

    9/264

    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

  • 8/4/2019 Matlab Module 1

    10/264

    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.

  • 8/4/2019 Matlab Module 1

    11/264

    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 formatcommand. 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 e 3.1416e+001

  • 8/4/2019 Matlab Module 1

    12/264

    format long 31.41592653589793

    format long e 3.141592653589793e+001

    format short g 31.416

    format long g 31.4159265358979

    format bank 31.42The following exercise will enable the readers to quickly write various mathematical formulas,

    interpreting error messages, and syntax related issues.

    e M1.1

    By using arbitrary values of , check that .

    Verify with a few arbitrary values of that .

    Verify with a few arbitrary values of that .

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

    e M1.2

    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.

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

    a.

    b. .

    Use MATLAB to calculate the magnitude and phase of for

  • 8/4/2019 Matlab Module 1

    13/264

    e M1.3

    Calculate the quantity for .

    Calculate for .

    nf, and NaN are predefined in MATLAB. NaN stands for Not-a-Number and results from undefined operations like

    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.

  • 8/4/2019 Matlab Module 1

    14/264

    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.1

    Command Usage

    cd, pwd To see the current directory

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

  • 8/4/2019 Matlab Module 1

    15/264

    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

    whatLists 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 spec

    byparentdir.

    When supplied with only dir_name, it creates new directory within the cu

    directory

    delete file_name

    delete *.mDeletes 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.

  • 8/4/2019 Matlab Module 1

    16/264

    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.

  • 8/4/2019 Matlab Module 1

    17/264

    Fig. M1.9 Entries in the Workspace

    Fig. M1.10 Array editor window

  • 8/4/2019 Matlab Module 1

    18/264

    Workspace related commands are listed in Table M1.2.

    Table M1.2

    Command Usage

    who Lists variables currently in the workspace

    whosLists 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 Editfrom 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.

    >> who

    Your variables are:

    A b

    >> whos

    Name Size Bytes Class

    A 3x4 96double

    array

    b 1x4 32 doublearray

    Grand total is 16 elements using 128 bytes

    Command History Window

    This 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

  • 8/4/2019 Matlab Module 1

    19/264

    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.

    MATLAB MODULE 1

    MATLAB Window Environment and the Base Program

    Getting Help

  • 8/4/2019 Matlab Module 1

    20/264

    MATLAB provides hundreds of built-in functions covering various scientificand engineering computations. With numerous built-in functions, it isimportant 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, awindow- based help is a good option. To activate the Help window,type helpwinor helpdeskon 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 commandnameto getdetailed task-oriented help. For example, type help helpwinin the commandwindow to get the help on the command helpwin.

  • 8/4/2019 Matlab Module 1

    21/264

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

    MATLAB has a wonderful demonstration program that shows its variousfeatures through interactive graphical user interface. Type demoat theMATLAB prompt to invoke the demonstration program (Fig. M1.14) and theprogram will guide you throughout the tutorials.

    Fig. M1.13 Help browser

  • 8/4/2019 Matlab Module 1

    22/264

    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, oroverwrites its current value if it already exists).

    >>A=[8 1 6 2;3 5 7 4;4 9 2 6]

  • 8/4/2019 Matlab Module 1

    23/264

    The blank spaces (or commas) around the elements of the matrix rowsseparate the elements. Semicolons separate the rows. For the abovestatement, 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 acolumn 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 ' , '. Forexample:

    >> b=[1,1,2,3]

    b =

    1 1 2 3

    We can determine the size of the matrices (number of rows, number ofcolumns) by using the size command.

    >> size(A)

    ans =

  • 8/4/2019 Matlab Module 1

    24/264

    3 4

    The command size, when used with the scalar option, returns the length ofthe dimension specified by the scalar. For example, size (A,1)returns thenumber 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 lengthcommand returns either number of rows or numberof columns, whichever is larger. For example,

    >> length(A)

    ans =

    4

    For vectors, length command can be used to determine its number ofelements.

    >> length(b)

    ans =

    4

    The use of colon ( : ) operator plays an important role in MATLAB. Thisoperator may be used to generate a row vector containing the numbers from agiven starting value xi, to the final value xf, with a specified increment dx,e.g., x=[xi:dx:xf]

    >> x=[0:0.1:1]

  • 8/4/2019 Matlab Module 1

    25/264

    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 thecommand linspace(x1,x2). By default, 100 samples will be generated. Thecommand 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 thecommand logspace .

    The colon operator can also be used to subscript matrices. Forexample, A(:,j) is thej

    thcolumn of A, and A(i,:)is the i

    throw 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

  • 8/4/2019 Matlab Module 1

    26/264

    >> 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 followingoperations:

    >> A+3

    >> A-3

    >> A*3

    >> A/3

  • 8/4/2019 Matlab Module 1

    27/264

    When you add/subtract/multiply/divide a vector/matrix by a number (or by avariable with a number assigned to it), MATLAB assumes that all elements ofvector/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

    Operation Operator Example Notes

    Plus + A+B Must be of same dimensions

    Minus - A-B Must be of same dimensions

    Multiply * A*B Must be of compatible dimensions

    Multiply (element-by-

    element).* A.*B

    Must be of same dimensions; multiplies element

    aij with element bij

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

    element bij

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

    element aij

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

    Matrix power (element-by-

    element).^ A.^k k 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:

  • 8/4/2019 Matlab Module 1

    28/264

    we write the equations in the matrix form as

    where

    is the matrix of coefficients of x1, x2and x3

    is the column vector which will contain the solutions x1, x

    2and x

    3

    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

  • 8/4/2019 Matlab Module 1

    29/264

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

    The minor mijof the element aij is the determinant of a matrix of

    order obtained from by removing the row and columncontaining aij. The cofactor cijof 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 kof matrixor arbitrary column lof matrix , we have

    or

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

    Following MATLAB commands solve the given set of simultaneous linearequations.

    >> A = [2 5 -3; 3 -2 4; 1 6 -4];

  • 8/4/2019 Matlab Module 1

    30/264

    >> b = [6; -2; 3];

    >> x = inv(A) * b

    x =

    4.8333

    -4.5833

    -6.4167

  • 8/4/2019 Matlab Module 1

    31/264

    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 Functions

    There are many flow control functions in MATLAB. The forfunction inMATLAB provides a mechanism for repeatedly executing a series ofstatements a given number of times. The forfunction connected toan endstatement sets up a repeating circulation loop. An important point isthat each formust be matched with anend. The breakstatement providesexit jump out of loop.

  • 8/4/2019 Matlab Module 1

    32/264

    The whilefunction in MATLAB allows a mechanism for repeatedly executinga series of statements an indefinite number of times, under control of a logicalcondition.

    The function if evaluates a logical expression and executes a group of

    statements based on the value of the expression. The elsestatement furtherconditionalizes the ifstatement.

    MATLAB MODULE 1

    MATLAB Window Environment and the Base Program

    Plotting

    MATLAB is an outstanding tool for visualization. In the following, we will learn how tocreate 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 aninterval of 0.05 sec. y- coordinate is the value of sinusoidal oscillations

    represented by . This plot can be generated by entering thefollowing 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

  • 8/4/2019 Matlab Module 1

    33/264

    Response is shown in graphics or figure window snapshot (Fig. M1.15).

    Arguments of thexlabel, ylabel, and titlecommands are text strings. Text strings are

    entered within single-quote characters. Lines beginning with %are comments; theselines are not executed. The printcommand sends the current plot to the printerconnected to your computer.

    Rather than displaying the graph as a continuous curve, one can show the unconnecteddata points. To display the data points with small stars, use plot(t,yt,'*'). To show theline through the data points in red color as well as the distinct data points, one cancombine the two plots with the command plot(t,yt,'r',t,yt,'*'). To learn more about plot

    options, typehelp ploton 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).

  • 8/4/2019 Matlab Module 1

    34/264

    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));

  • 8/4/2019 Matlab Module 1

    35/264

    >> 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-nmatrix of smallaxes and selects the pth axes for the current plot. Labeling, title, and grid commandsshould be given immediately after the particular subplotcommand 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 theplot to open the Property Editor - Axeswindow (Fig M1.17). Using thisproperty 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

  • 8/4/2019 Matlab Module 1

    36/264

    are: Line, Area, Bar, Stairs, and Stem. Line width and markers can be changed by pulldown menu Lineand Marker.

    Fig. M1.17 Axes property editor

    Fig. M1.18 Lineseries property editor

  • 8/4/2019 Matlab Module 1

    37/264

    rcise M1.7

    erate 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.

    h the plots should be with respect to time. In both the plots, mark each curve with its kand values

    nt: UseInsert Text Box option from main menu bar). From the main menu bar, choose Tools Edit Plot andk 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. Clickin

    cross-hair on the curve will give corresponding and axis values. Use Data Cursor to observe values at various tim

    rcise M1.8

    ign 0.5, , and to , respectively. Calculate for t=.1:10].

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

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

    rcise 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 s

  • 8/4/2019 Matlab Module 1

    38/264

    graph sheet for . Use subplot. Title both the plots, label the axes, and generate grid

    a)

    b)

    t: Use logspace command to generate 100 logarithmically spaced samples of between 0.01 and 1000 rad/sec.

    abs and angle commands for calculations as per ii(a) and ii(b) given above for each Use semilogxto plot.

    MATLAB Window Environment and the Base Program

    Script files (M-files)

    Type edit on MATLAB prompt and hit enter (or follow File New M-

    Fileoption 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 withsequences of MATLAB commands) in files called M- files. An example M-fileis shown in Fig. M1.19.

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

  • 8/4/2019 Matlab Module 1

    39/264

    >> 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 thecommand rmpath . Learn more about MATLAB search path through onlinehelp.

    Type simply the name of the file decayed_sin to execute it from thecommand window. Script can also be saved and executed simultaneously by

    clicking the icon in the main toolbar.

    To open the existing M-filefrom the MATLAB command window,

    type edit filename(or follow File Open option from the main menu bar orclick on icon in the main toolbar).

    All variables created during the runtime of the script file are left in theworkspace. Using who orwhos , you can get information about them, andalso access them by workspace window.

    ercise M1.10

    odify 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 amplitudthe sine wave.

    3. It should plot the Yt curve; however, wherever Yt crosses the zero-axes, an indication through x -mark shouldappear.

    4. Display current date and time at the end. (Hint: Learn commands dateand clockusing online help).

    5. Calculate the total execution time of the program. (Hint: Learn ticand toccommands).

    ercise M1.11

  • 8/4/2019 Matlab Module 1

    40/264

    arn more about 1) Forloops, 2) WhileLoops, and 3) If-Else-Endconstructions using online help.

    Fig. M1.19 Example M-file

    MATLAB Window Environment and the Base Program

  • 8/4/2019 Matlab Module 1

    41/264

    Developing user-defined Functions

    Suppose you want to write a function to generate and plot Ndata points of theexponentially-decaying sinusoid of amplitude A, frequency f, and exponential

    time-constant . A MATLAB function which can take all these parameters asarguments 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 tosave the file, editor will automatically assign a function name decaying_sin toyour M-file. Save the function to the current working directory or include yourpersonal directory into MATLAB search path by using addpath command. Wemust avoid duplicating function names with built-in MATLAB functions orkeywords.

    A function file begins with a function definition line, which contains thekeyword function, a well-defined list of input and output arguments, andfunction 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 H1line.This line is automatically catalogued in the contents.m file of the directory inwhich function file resides. This allows the line to be searched bythelookfor command. Very carefully chosen keywords related to your functionshould come in the H1 line. Note that if there is any blank space beforethe % sign in the H1line, then it is no longer H1line!!

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

    >> help decaying_sin

    and see what MATLAB displays.

  • 8/4/2019 Matlab Module 1

    42/264

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

  • 8/4/2019 Matlab Module 1

    43/264

    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, andptsmust bedefined before the function call.

    >> res = decaying_sin ([0 10], tau, 3, 50, 1000)

    Here the input variable taumust be defined beforehand; all other inputs have beendefined 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.

  • 8/4/2019 Matlab Module 1

    44/264

    Exercise M1.12

    1. Execute decaying_sin function with less than four and greater than five arbitrary arguments and interpret the messa

    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 functio

    Modify the above function with one more input argument str' to provide control over whether we want to generate

    plot or not? Ifstr = Y'or y', then it should generate the plot. Ifstr = N'or n', then it should not. If any other charac

    is passed, then it should give the error message Unrecognized user input'and terminate the program. You also nee

    modify processing with the nargin command.

    Exercise M1.13

    Write a function named specifications with the following input and output arguments:

    nput 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:

    . Yt calculated by

    2. Tau calculated by

    3. Tr calculated by

    4. Tp calculated by

  • 8/4/2019 Matlab Module 1

    45/264

    5. Mp calculated by

    MATLAB MODULE 4

    Feedback System Simulation

    Transfer Function Manipulation

    Suppose we have developed mathematical models in the form of transferfunctions for the plant, represented by G(s), and the controller, representedby D(s), and possibly many other system components such as sensors andactuators. Our objective is to interconnect these components to form blockdiagram 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 feedbackcommands:

    series(G,D)for a cascade connection of G(s) and D(s); parallel(G1,G2) for aparallel connection of G1(s) andG2(s); feedback(G,H, sign)for a closed-loopconnection with G(s) in the forward path and H(s) in the feedback path;and signis -1 for negative feedback or +1 for positive feedback (the sign is

    optional for negative feedback); and cloop(G,sign)for a unity feedbacksystem 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*Dfor a cascade connection of G(s) and D(s); G1+G2for a parallelconnection of G1(s) and G2(s);G/(1+G*H)for a closed-loop negative feedback

  • 8/4/2019 Matlab Module 1

    46/264

    connection with G(s) in the forward path and H(s) in the feedback path;and G/(1-G*H)for positive feedback systems.

    MATLAB MODULE 4

    Feedback System Simulation

    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 inputR(s)and control U(s), etc. It is now easy to use some of the control analysiscommands available from the Control SystemToolbox. impulse(M) and step(M) commands represent common controlanalysis operations that we meet in this book. Also frequently used in thebook are frequency-response plots.

    Example M4.1

    Consider the block diagram in Fig. M4.1.

    Fig. M4.1

  • 8/4/2019 Matlab Module 1

    47/264

    For value of gain KA= 80, the following two MATLAB sessions evaluate thestep responses with respect to reference input R(s) and disturbancesignal 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 byright clicking on the plot and selecting Grid option.

  • 8/4/2019 Matlab Module 1

    48/264

    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 + 400000

  • 8/4/2019 Matlab Module 1

    49/264

    and 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 thetransfer function

    The system sensitivity to parameter Kis

  • 8/4/2019 Matlab Module 1

    50/264

    Figure M4.4 shows the magnitudes of and versusfrequency for K= 0.25; generated using the following MATLAB script. Textarrows have been introduced in the plot by following Insert from the mainmenu and selecting the option Text Arrow.

    Note that the sensitivity is small for lower frequencies, while the transferfunction 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

  • 8/4/2019 Matlab Module 1

    51/264

    Of course, the sensitivity Sonly represents robustness for small changes ingain K. If Kchanges from 1/4 within the range K= 1/16 to K= 1, the resultingrange of step responses, generated by the following MATLAB script, is shownin Fig. M4.5. This system, with an expected wide range of K, may not beconsidered adequately robust. A robust system would be expected to yieldessentially the same (within an agreed-upon variation) response to selectedinputs.

    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);

  • 8/4/2019 Matlab Module 1

    52/264

    Fig. M4.5

    MATLAB MODULE 4

    Feedback System Simulation

    Simulink Simulation

    Simulink simulation is an alternative to block diagram manipulation followedby time-response analysis. From the Simulink model of a control system,output yin response to command r, output yin response to disturbance w,control uin response to command r, and all other desired internal variablescan be directly obtained.

  • 8/4/2019 Matlab Module 1

    53/264

    Example M4.3

    Control system design methods discussed in this course are based on theassumption of availability of linear time invariant (LTI) models for all thedevices in the control loop.

    Consider a speed control system. The actuator for the motor is a poweramplifier. An amplifier gives a saturating behaviour if the error signal input tothe amplifier exceeds linear rangevalue.

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

    Figure M4.6 is the simulation diagram of a feedback control system: theamplifier 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 ofthe simulation is shown in Fig. M4.7.

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

    Fig. M4.6 (download )

    http://nptel.iitm.ac.in/courses/Webcourse-contents/IIT-Delhi/Control%20system%20design%20n%20principles/matlab/simulink/m4_3.mdlhttp://nptel.iitm.ac.in/courses/Webcourse-contents/IIT-Delhi/Control%20system%20design%20n%20principles/matlab/simulink/m4_3.mdlhttp://nptel.iitm.ac.in/courses/Webcourse-contents/IIT-Delhi/Control%20system%20design%20n%20principles/matlab/simulink/m4_3.mdlhttp://nptel.iitm.ac.in/courses/Webcourse-contents/IIT-Delhi/Control%20system%20design%20n%20principles/matlab/simulink/m4_3.mdl
  • 8/4/2019 Matlab Module 1

    54/264

    Time and Output response data have been transferred to workspace using ToWorkspaceblock from Sinksmain block menu. Clockblock is availablein Sourcesmain menu. These variables are stored in thestructureOutputand Timein the workspace, along with the informationregarding 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 toaccess Output.signals.valuesand Time.signals.values. The step responseplot has been generated by the following MATLAB script.

    >> plot(Time.signals.values,Output.signals.values)

    >> xlabel('Time (sec)');

    >> ylabel('Output');

    >> title('Step Response');

  • 8/4/2019 Matlab Module 1

    55/264

    Fig. M4.7

    Example M4.4

    In this example, we simulate a temperature control system with measurementnoise added to the feedback signal. The process transfer function is

    The deadtime minutes. The measurement noise parameters we haveused 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 blockin this figure is Transport Delay block from Continuous library, and RandomNumberblock is from Sources library.

  • 8/4/2019 Matlab Module 1

    56/264

    Fig. M4.8 (download )

    The data has been transferred to the workspace using To Workspaceblock.

    The step response, generated using the following MATLAB script is shown inFig. M4.9.

    >> plot(Time.signals.values,Y.signals.values);

    >> ylabel('Output (Y)');

    >> xlabel('Time(min)');

    >> title('Step Response');

    http://nptel.iitm.ac.in/courses/Webcourse-contents/IIT-Delhi/Control%20system%20design%20n%20principles/matlab/simulink/m4_4.mdlhttp://nptel.iitm.ac.in/courses/Webcourse-contents/IIT-Delhi/Control%20system%20design%20n%20principles/matlab/simulink/m4_4.mdlhttp://nptel.iitm.ac.in/courses/Webcourse-contents/IIT-Delhi/Control%20system%20design%20n%20principles/matlab/simulink/m4_4.mdlhttp://nptel.iitm.ac.in/courses/Webcourse-contents/IIT-Delhi/Control%20system%20design%20n%20principles/matlab/simulink/m4_4.mdl
  • 8/4/2019 Matlab Module 1

    57/264

    Fig. M4.9

    The performance of the system with measurement noise removed, is shown inFig. M4.10. To remove the effect of noise, simply disconnect the Random

    numberblock from the Sumblock in the feedback path.

  • 8/4/2019 Matlab Module 1

    58/264

    Fig. M4.10

    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 controlsystems' analysis and design. We will be using only some of these

  • 8/4/2019 Matlab Module 1

    59/264

    commands, because of the limited nature of course profile. Description ofthese commands will be distributed in different modules.

    In this module, we will present commands related to transfer functions andsystem responses. To see all the commands in the Control System Toolbox

    and their functionalities, type help controlin the MATLAB command window.MATLAB will respond with

    >> help control

    Control System ToolboxVersion 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.

  • 8/4/2019 Matlab Module 1

    60/264

    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.

  • 8/4/2019 Matlab Module 1

    61/264

    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.

  • 8/4/2019 Matlab Module 1

    62/264

    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.

  • 8/4/2019 Matlab Module 1

    63/264

    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 theMATLAB, partial fraction expansion of rational expressions, representation oftransfer functions as LTI objects, and to obtain time domain responses of LTIsystems. Important commands for this module are:

    roots Find polynomial rootspoly 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 datazpkdata 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

  • 8/4/2019 Matlab Module 1

    64/264

    lsim Simulate time response of LTI models to arbitrary inputs

    gensig Periodic signal generator for time response simulations with lsim

    Polynomials

    Consider a polynomial s3 +3 s2 +4', to which we attach the variable name p.MATLAB can interpret a vector of length n+1 as the coefficients of an nth -order polynomial. Coefficients of the polynomial are interpreted in descendingpowers. Thus, if the polynomial is missing any coefficient, we must enterzeros in the appropriate places in the vector. For example, polynomial pcanbe represented by the vector [1 3 0 4]in MATLAB. For example:

    >> p=[1 3 0 4]

    p =

    1 3 0 4

    Roots of the polynomial can be obtained by rootscommand.

    >> 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 canbe obtained by the commandpoly.

    >> p=poly(r)

    p =

    1.0000 3.0000 0.0000 4.0000

    Use the command polyval(p, s) to evaluate the polynomial represented byvector p at arbitrary value of s. For example, to evaluate the polynomial

    's3 +3 s2 +4' at , type

  • 8/4/2019 Matlab Module 1

    65/264

    >> polyval(p,sqrt(2))

    ans =

    12.8284

    The product of two polynomials is found by taking the convolution of theircoefficients. The function conv will do this for us. Consider an example ofmultiplying polynomial s3 +3 s2 +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 asthe 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.

  • 8/4/2019 Matlab Module 1

    66/264

    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 areintegers.A fraction of the form G(s) can be expanded into partial fractions. Todo 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. Thecommand [A,p,K]=residue(N,D) returns residues in column vector A, theroots 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:

  • 8/4/2019 Matlab Module 1

    67/264

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

    If , Kis empty (zero).

    Supplying 3 arguments A, p, and K to residue converts the partial fractionexpansion 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 =

  • 8/4/2019 Matlab Module 1

    68/264

    [ ]

    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

  • 8/4/2019 Matlab Module 1

    69/264

    -1.0000

    0

    K =

    [ ]

    rcise M2.3

    resent the matrices A, p, and K obtained in Example M2.1 in partial fraction form and convert back to the polynom

    m. Counter check your answer with MATLAB.

    rcise M2.4

    sider the rational fraction:

    ain partial fraction form in terms ofK. Solve using MATLAB for and countercheck your answer.

    rcise M2.5

    sider the rational fraction: .

    ntify the points where:

    and

    e: The roots of the numerator polynomial, i.e. , , are known as thezeros of and the roots of the

    ominator polynomial, i.e. , , are known as the poles of

  • 8/4/2019 Matlab Module 1

    70/264

    Transfer Functions

    Transfer functions can be represented in MATLAB as LTI (Linear TimeInvariant) objects using numerator and denominator polynomials. Consider

    the transfer function given by It can be represented inMATLAB 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 followingMATLAB session for the transfer function

    >> n1 = [5 1];

  • 8/4/2019 Matlab Module 1

    71/264

    >> 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 tfin MATLABcommand window. Type ltiprops tfon MATLAB prompt to learn the propertiesassociated with an LTI object represented by tf.

    Transfer functions can also be entered directly in polynomial form as we enterthem in the notebook using LTI objects. For example, observe the followingMATLAB session.

    >> s=tf('s') %Define 's' as an LTI object in polynomial form

    Transfer function:

    s

    >> G1=150*(s^2+2*s+7)/[s*(s^2+5*s+4)] % Form G1(s) as an LTI transferfunction

  • 8/4/2019 Matlab Module 1

    72/264

    % 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 poleand zerocalculate the poles and zeros of LTI models.

    >> pole(G1)

    ans =

    0

    -4

    -1

    >> zero(G1)

    ans =

    -1.0000 + 2.4495i

    -1.0000 - 2.4495i

    To extract numerator and denominator polynomials, use the function tfdata .

    >> [num,den]=tfdata(G,'v')

  • 8/4/2019 Matlab Module 1

    73/264

    num =

    0 1 1

    den =

    1 3 1

    To extract zeros and poles of transfer function simultaneously, use thefunction 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 transferfunction of LTI system can be constructed by zpkcommand. 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 tfcan be converted to zero-pole-gain model by the commandzpkand vice versa. The following MATLABsession gives the zero-pole-gain format of LTI system represented by G(s).

    >> zpk(G)

    Zero/pole/gain:

  • 8/4/2019 Matlab Module 1

    74/264

    (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 zpkin MATLAB

    command window. Typeltiprops zpkon MATLAB prompt to learn theproperties associated with an LTI object represented by zpk.

    The function pzmap(G)plots the poles and zeros of the transferfunction G(s) on complex plane. When used with two left hand sidearguments, [p,z] = pzmap(G), the function returns the poles and zeros of thesystem in two column vectors pand 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 thecommands stepand impulse. For example, to obtain the step response ofthe system represented in LTI object G, enter

  • 8/4/2019 Matlab Module 1

    75/264

    >> step(G)

    The MATLAB response to this command is shown in Fig. M2.1.

    Fig. M2.1

    To obtain the impulse response, enter

    >> impulse(G)

    The MATLAB response to this command is shown in Fig. M2.2.

  • 8/4/2019 Matlab Module 1

    76/264

    Fig. M2.2

    Step and impulse response data can be collected into MATLAB variables byusing two left hand arguments. For example, the following commands willcollect step and impulse response amplitudes in ytand time samples in t.

    [yt, t] = step(G)

    [yt, t] = impulse(G)

    Response of LTI systems to arbitrary inputs can be obtained by thecommand lsim. The command lsim(G,u,t)plots the time response of the LTI

    model G to the input signal described by uand t. The time vector tconsists ofregularly spaced time samples and uis a matrix with as many columns asinputs and whose i

    th-row specifies the input value at time t(i). Observe the

    following MATLAB session to obtain the time response of LTI system Gtosinusoidal input of unity magnitude.

    >> t=0:0.01:7;

  • 8/4/2019 Matlab Module 1

    77/264

    >> 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.

  • 8/4/2019 Matlab Module 1

    78/264

    The function gensiggenerates periodic signals for time response simulationwith lsimfunction. It can generate sine, square, and periodic pulses. Allgenerated signals have unit amplitude. Observe the following MATLABsession to simulate G( s) for 20 seconds with a sine wave of period 5seconds.

    >> [u,t]=gensig( 'sin' ,5,20); %Sine wave with period 5 sec and duration20 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

  • 8/4/2019 Matlab Module 1

    79/264

    Generate square and pulse signals with the period of 4 seconds and obtain time response offor a duration of 30 seconds.

    Example M2.3

    The following MATLAB script calculates the step response of second-ordersystem

    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)' )

  • 8/4/2019 Matlab Module 1

    80/264

    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-ordersystem

    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];

  • 8/4/2019 Matlab Module 1

    81/264

    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.

  • 8/4/2019 Matlab Module 1

    82/264

    Fig. M2.6

    Right-clicking away from the curves obtained

    by step, impulse, and lsimcommands brings up a menu. From this menu,various time-response characteristics can be obtained and plotted on thegraph ( Discussion on time-response characteristics will appear later inModule 5).

    MATLAB MODULE 2

    Control System Toolbox and Symbolic Math Toolbox

    Symbolic Math Toolbox

    MATLAB's Symbolic Math (Symbolic Math ematics) toolbox allows users to performsymbolic mathematical computations using MATLAB. The only basic requirement is todeclare symbolic variables before they are used. For control systems analysis anddesign, symbolic math toolbox is particularly important because of the following:

    1. Transfer functions and other expressions can be entered in symbolic form as wewrite 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 symbolicon the MATLAB command prompt to see all the functionalitiesavailable 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 calculatinginverse Laplace transform. The following MATLAB session gives the stepsperformed during the calculation of inverse Laplace transform

    of using Symbolic Math.

  • 8/4/2019 Matlab Module 1

    83/264

    xercise M2.8

    tialize s and T as symbols. Using Symbolic Math tools, find the response of the first- order system ,w

    e step excitation of strengthA .

    nt: Find the inverse Laplace transform of .

    xercise M2.9

  • 8/4/2019 Matlab Module 1

    84/264

    nd manually the Laplace transform of . Using Symbolic Math tools, declare t as symbolicriable 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 ofterms. simplify(G)can be used to combine partial fractions. Symbolic Math toolbox alsocontains 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 termsof 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 fractionalsymbolic 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))

  • 8/4/2019 Matlab Module 1

    85/264

    .............4--------------------s (s + 4) (s + 1)

    In the above example, the symbolic fractions 1/3 and 4/3 will be converted to 0.333 and1.33 if the argumentplacesin vap(G, places)is set to 3.

    >> pretty(vpa(G,3))

    ............0.333 ....1.331/s + ---------- - ----------........... s + 4. ....s + 1.

    ise M2.10

    der the function . Show using Symbolic Math tools that the simplified form of its

    orm is .

    Basic mathematical operators +, , , and are applicable to symbolicobjects 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 canbe 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 =

  • 8/4/2019 Matlab Module 1

    86/264

    5/2*K/s/(s+5)/(1+5/2/s/(s+5)/(1/10*s+1))

    >> pretty(M)

    K

    5/2 ------------------------------------------/ 1 \

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

    \ s (s + 5) (1/10 s + 1) /

    >> pretty(simplify(M))

    (s + 10) K

    5/2 -------------------------

    3 2

    s + 15 s + 50 s + 25

    With Symbolic Math toolbox, symbolic transfer functions can easily beconverted to the LTI (Linear Time-Invariant) transfer function objects. Thisconversion is done in two steps. The first step uses the commandnumden toextract the symbolic numerator and denominator of G(s). The second stepconverts, separately, the numerator and denominator to vectors using thecommand sym2poly . The last step consists of forming the LTI transferfunction object by using the vector representation of the transfer function'snumerator and denominator. The command sym2poly doesn't work onsymbolic expressions with more than one variable.

    As an example, we form the LTI object from obtained in the aboveexample with .

  • 8/4/2019 Matlab Module 1

    87/264

  • 8/4/2019 Matlab Module 1

    88/264

    The command poly2symconverts polynomial coefficient vectors to symbolicpolynomial. Learn more about poly2symusing online help.

    MATLAB MODULE 3

    Simulink

  • 8/4/2019 Matlab Module 1

    89/264

    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 functionsfrom a given block diagram. However, as we shall shortly see, the simulationenvironment provided by MATLABs Simulink Toolkit obviates the need for blockdiagram reduction. The Simulink model mimics the block diagram of a feedback controlsystem and is used to evaluate the response of controlled variable to any test input. Italso 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 thebackbone of any realistic control design. A Simulink model based on the structure andparameters of the system model is constructed. The responses of the actual systemand its Simulink model are obtained using a set of test inputs. If the actual responses tothe test inputs were significantly different from the Simulink responses, certain modelparameters would have to be revised, and/or the model structure would have to berefined to better reflect the actual system behaviour. Once satisfactory modelperformance has been achieved, various control schemes can be designed andimplemented.

    In practice, it is best to test a control scheme off-line by evaluating the systemperformance in the safety of the Simulink environment. The key components of acontrol system include actuators, sensors, and the plant/process itself. A decision toinclude 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 themodel may result in a more complicated controller design, which will ultimately increasethe cost and sophistication of the system. The design is usually carried out using anapproximated model; the evaluation of the design is done on the true model, whichincludes nonlinearities, and other aspects neglected in the approximate model. Simulinkis an excellent tool for this evaluation.

    SIMULINK (SIMUlation LINK) is an extension of MATLAB for modeling, simulating, andanalyzing dynamic, linear/nonlinear, complex control systems. Graphical User Interface(GUI) and visual representation of simulation process by simulation block diagrams aretwo key features which make SIMULINK one of the most successful software packages,particularly suitable for control system design and analysis.

  • 8/4/2019 Matlab Module 1

    90/264

    Simulation block diagrams are nothing but the same block diagrams we are using todescribe control system structures and signal flow graphs. SIMULINK offers a largevariety of ready-to-use building blocks to build the mathematical models and systemstructures 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 outputdata will be displayed.

    Because SIMULINK is graphical and interactive, we encourage you to jump right in andtry it. To help you start using SIMULINK quickly, we describe here the simulationprocess through a demonstration example with MATLAB version 7.0, SIMULINK version6.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 toconstruct simulation block diagrams. You can expand/collapse the tree by

    clicking on the boxes beside each node and block in the block set pan.

  • 8/4/2019 Matlab Module 1

    91/264

    Fig. M3.2 SIMULINK Library Browser

    Expand the node labeled Simulink. Subnodes of this node ( Commonly UsedBlocks, Continuous, Discontinuities,Discrete, Logic and Bit Operations, etc) are

    displayed. Now for example, expanding the Sourcessubnode displays a long list of

  • 8/4/2019 Matlab Module 1

    92/264

    Sources library blocks. Simply click on any block to learn about its functionality in thedescription box (see Fig. M3.3).

    Fig. M3.3 Blocks in Sources subnode

  • 8/4/2019 Matlab Module 1

    93/264

    You may now collapse the Sourcessubnode, and expand the Sinkssubnode. A listof Sinkslibrary block appears (Fig.M3.4). Learn the purpose of various blocksin Sinkssubnode by clicking on the blocks.

    Fig. M3.4 Blocks in Sinks subnode

    ercise M3.1

  • 8/4/2019 Matlab Module 1

    94/264

    pand the Continuous, Discontinuities, Discrete, and Math Operationssubnodes. Study the purpose of various bl

    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 otherlibraries as well. You can also customize and create your own blocks. For informationon 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 asimulation diagram. In the SIMULINK library browser, follow File NewModel or hit Ctrl+N to open an untitled' workspace (Fig.M3.5) to build up aninterconnection 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

  • 8/4/2019 Matlab Module 1

    95/264

    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

    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

    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 blockdiagram of Fig. M3.6. This is given in Fig. M3.7.

  • 8/4/2019 Matlab Module 1

    96/264

    Fig. M3.7 SIMULINK blocks required for implementation

    Identifying the block(s) required for simulation purpose is in fact the first step of theconstruction of simulation diagram in SIMULINK. The next step is to drag and

    dropthe required blocks from SIMULINK block libraries to untitledworkspace. Let usput the very first block for applied voltage (Ea) to workspace.

    Expand the Sourcessubnode, move the pointer and click the block labeled Constant,and while keeping the mouse button pressed down, drag the block and drop it inside theSimulation 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 untitledW

    them as shown in Fig. M3.9.

  • 8/4/2019 Matlab Module 1

    97/264

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

    Fig. M3.9 Unconnected blocks in Workspace

  • 8/4/2019 Matlab Module 1

    98/264

    It is visible that all the block parameters are in their default settings. For

    example, the default transfer function of Transfer Fcnblock is anddefault signs of Sum block are + +. We need to configure these blockparameters to meet our modeling requirements. It is straightforward. Doubleclick the block to set up its parameters. For example, double clickingthe Transfer Fcn block opens the window titled Block Parameters: TransferFcn, 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 .

  • 8/4/2019 Matlab Module 1

    99/264

    To enhance the interpretability of simulation diagram, we can also change theblock identification name. Simply click on the textTransfer Fcn to activate thesmall window around the text to change the block name. For our simulationblock diagram, the suitable text for Transfer Fcn block may be Armaturecircuit.

    Before we move to the last step of interconnecting the blocks as per thedesired structure, just finish Exercise M3.3. Note thattheDecimation parameter value by default is 1. Increasing this value reducesthe number of data samples taken over the simulation time. We have used thedefault 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 theblocks.

    Lines are drawn to interconnect these blocks as per the desired structure. Aline can connect output port of one block to the input port of another block. Aline can also connect the output port of one block with input ports of manyblocks by using branch lines. We suggest readers to perform the following

    line/block operations on blocks dragged in workspace to get hands onpractice.

    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.

  • 8/4/2019 Matlab Module 1

    100/264

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

    Another simple methodology doesn't require dragging the line. Block1 outputport 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 thesame 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 cursorshape changes to cross hair.

    3. Release the control key, while pressing down the left mouse button; drag the pointerto 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:

  • 8/4/2019 Matlab Module 1

    101/264

    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 dragthe 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 thedeveloped 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 completesimulation diagram is shown in Fig. M3.11.

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

  • 8/4/2019 Matlab Module 1

    102/264

    Fig. M3.11 Final simulation diagram(download )

    http://nptel.iitm.ac.in/courses/Webcourse-contents/IIT-Delhi/Control%20system%20design%20n%20principles/matlab/simulink/M3.mdlhttp://nptel.iitm.ac.in/courses/Webcourse-contents/IIT-Delhi/Control%20system%20design%20n%20principles/matlab/simulink/M3.mdlhttp://nptel.iitm.ac.in/courses/Webcourse-contents/IIT-Delhi/Control%20system%20design%20n%20principles/matlab/simulink/M3.mdlhttp://nptel.iitm.ac.in/courses/Webcourse-contents/IIT-Delhi/Control%20system%20design%20n%20principles/matlab/simulink/M3.mdl
  • 8/4/2019 Matlab Module 1

    103/264

    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 angularvelocity variation with time. Click the autoscale icon in the displaywindow to scale the axes as per the variable ranges. Autoscaled scopedisplay is shown in Fig. M3.14. With zoom facility, try zooming the portion ofgraph between 0.5 to 1 sec, and 20 to 25 unit angular velocity to identify thenumerical value of angular velocity at 0.8 seconds.

  • 8/4/2019 Matlab Module 1

    104/264

    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 maximumvalue for the y-axis. In Title, enter the title of the plot. See Fig. M3.15.

  • 8/4/2019 Matlab Module 1

    105/264

    Fig. M3.15 Scope axis properties editor

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

    Click on the Data history button. If you want input-output data from this scopeto be available to MATLAB workspace for further analysis, check thebutton Save data to workspace. In the box Variable name, enter thevariable name for saving the data. By default it will save the data with variablename ScopeData. With the pop-down menu Format, select the format inwhich 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 timesteps. Type the following commands in your MATLAB prompt andobserve the outputs.

  • 8/4/2019 Matlab Module 1

    106/264

    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 seethe information stored in the field signals, type:

    >> ScopeData.signals

    ans =

    values: [4663x1 double]

  • 8/4/2019 Matlab Module 1

    107/264

    dimensions: 1

    label: ''

    title: ''

    plotStyle: 0

    It indicates that the field signalscontains subfield values, which is of 4663 x 1 sizevector containing the values of angular velocity. Try accessing the

    field timeof ScopeData.

    Exercise M3.5

    Plot the angular velocity against time using the plotcommand. Give suitable title to the plot and labels to x andy axes.

    Hint: You need to plot ScopeData.signals.valuesagainst ScopeData.time.

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