intro matlab&simulink

12
Introduction to MATLAB MATLAB is a interactive software package for scientific and engineering numeric computation. MATLAB covers such topics as numerical analysis, matrix computation, signal processing and graphics in an easy to use environment. In addition to this, there are various 'toolboxes' which enable the user to access commands for more specialised operations. Problems and solutions are expressed in a similar manner to how they would be written mathematically.  The basic data element of MATLAB is the matrix that does not require dimensioning. Indeed the original MATLAB (Matrix laboratory) arose from the need to deal with matrix computations but now extends well beyond this. I. Basic Use and Features 1. Invoking and Terminating MATLAB Simply start MATLAB in the same way as any Windows package. On starting, the MATLAB prompt (>>) should appear. To finish MATLAB, either enter quit or exit at the MATLAB prompt or leave by a usual Windows operation. 2. The Help Facility Click Help on the pull down menu to obtain an introduction to the facility. 3. The MATLAB Search Path MATLAB has a search path, which indicates where it should look for files etc. The path can be seen by entering: >> path Other folders can be added to the path by entering: >> addpath full-filename  This is useful when wishing for easy access to user generated 'm-files' (see later). 4. The Command line and Command Line Editor • Once the prompt has been obtained, expressions can be entered on the 'command line'. Intro-Matlab&Simulink.doc 1

Upload: narendhran-thangavel

Post on 07-Apr-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Intro Matlab&Simulink

8/3/2019 Intro Matlab&Simulink

http://slidepdf.com/reader/full/intro-matlabsimulink 1/12

Introduction to MATLAB

MATLAB is a interactive software package for scientific and engineeringnumeric computation. MATLAB covers such topics as numerical analysis,matrix computation, signal processing and graphics in an easy to useenvironment. In addition to this, there are various 'toolboxes' whichenable the user to access commands for more specialised operations.Problems and solutions are expressed in a similar manner to how theywould be written mathematically.

 The basic data element of MATLAB is the matrix that does not requiredimensioning. Indeed the original MATLAB (Matrix laboratory) arose fromthe need to deal with matrix computations but now extends well beyondthis.

I. Basic Use and Features

1. Invoking and Terminating MATLAB

Simply start MATLAB in the same way as any Windows package. Onstarting, the MATLAB prompt (>>) should appear. To finish MATLAB,either enter quit or exit at the MATLAB prompt or leave by a usual

Windows operation.

2. The Help Facility

Click Help on the pull down menu to obtain an introduction to the facility.

3. The MATLAB Search Path

MATLAB has a search path, which indicates where it should look for filesetc. The path can be seen by entering:

>> path

Other folders can be added to the path by entering:

>> addpath full-filename

 This is useful when wishing for easy access to user generated 'm-files'(see later).

4. The Command line and Command Line Editor

• Once the prompt has been obtained, expressions can be entered on the

'command line'.

Intro-Matlab&Simulink.doc

1

Page 2: Intro Matlab&Simulink

8/3/2019 Intro Matlab&Simulink

http://slidepdf.com/reader/full/intro-matlabsimulink 2/12

• The usual 'arrow keys', with the 'delete' and 'backspace' keys, on thekeypad can be used to edit the command line and so correct, forexample, typing errors. The 'up arrow' (↑) can be used to recallpreviously typed complete commands. Note that a command is onlyacted on when it is on the current input line (i.e. the last line on the

screen) and the 'return' key has been hit.

5. Operators, Statements and Variables

• The usual mathematical operators are available for normal matrixoperations:

+ addition- subtraction* multiplication/ division^ power

together with parentheses, ( ).

• In addition, the basic matrix operations are modified for element-byelement operations by preceding the operator with a period (i.e. a fullstop). These are known as 'array operations' and are useful, for example,with graphics:

.* multiplication./ division

.^ power

• Variables must begin with a letter and can be any length but only thefirst 19 characters are recognised. Note: MATLAB is case sensitive.

• Variables are assigned in the following form:

>> Variable = expression

• Matrices are entered using square brackets, with semi-colons toseparate rows and spaces to separate elements.

e.g. >>A=[1 2 3;4 5 6]

would produce on the screen,

A =1 2 34 5 6

Variables are assigned as scalars or arrays as required for their use.Assignment of array dimensions is not required.

Intro-Matlab&Simulink.doc

2

Page 3: Intro Matlab&Simulink

8/3/2019 Intro Matlab&Simulink

http://slidepdf.com/reader/full/intro-matlabsimulink 3/12

• Matrix elements are referred to by using normal parentheses, in rowand column order.

e.g. in the above matrix,

>>x=A(2,1)

produces, x =4

• The prime symbol (i.e. a dash or single quote) is used for a matrixtranspose.

e.g. >>B=[5 6;7 8]'

produces, B =5 76 8

• To suppress screen output, the expression is terminated with a semi-colon.

• MATLAB can be used in 'calculator mode'

e.g. >>12.4/6.9

produces, ans =1.7971

Note: the results of all expressions, where a variable has not beenassigned, is stored in the variable: 'ans'.

• Once data value has been entered, it remains in a workspace area until

changed or cleared.

6. Common Built-In Functions

 The help facility gives a full description of these as well as otherfunctions. (see help for details of the parameters used in the particularfunction):

abs - absolute valueaxis - specifies manual axis scaling on plotsclear - clears the workspace

clg - clear the graph windowcos - computes the cosine

Intro-Matlab&Simulink.doc

3

Page 4: Intro Matlab&Simulink

8/3/2019 Intro Matlab&Simulink

http://slidepdf.com/reader/full/intro-matlabsimulink 4/12

diary - saves the session on a disk fileexp - exponential with base eeye - generates identity matrixgrid - adds a grid to the current graphhelp - prints a list of help topics

inv - inverse of a square matrixload - loads variables saved in a filelog - natural loglog10 - log base 10max - maximum valuemin - minimum valueplot - generates a linear plotpolyval - evaluates a polynomialroots - determines roots of a polynomialsin - computes the sinesqrt - square roottan - tangenttext - adds text to current graphtitle - adds a title to current graph

xlabel - adds a label to the x-axis of thecurrent graph

ylabel - adds a label to the y-axis of the currentgraph

zeros - generates a matrix of zeros

7. Colon Notation

• This is used for generating array elements in the following form,

x = [ starting value: increment : final value]

For example, suppose a plot of y=x sin(x) is required for 0 x 1.0 in  increments of 0.1.

>>x=[0:0.1:1.0]';>>y=x.*sin(x)>>plot(x,y)

 The colon can also be used to refer to all columns or rows of an array.

e.g. >>a = b(:,3)

assigns 'a' to be the elements of column 3 in the multidimensional array,'b'.

8. Polynomials

• Polynomials are referred to by a vector whose elements are the

coefficients of the polynomial in descending powers. The vector can thenused in the required polynomial function.

Intro-Matlab&Simulink.doc

4

Page 5: Intro Matlab&Simulink

8/3/2019 Intro Matlab&Simulink

http://slidepdf.com/reader/full/intro-matlabsimulink 5/12

For example, to evaluate the polynomial, p(s)=3s2+2s+1 at s=5

>>p=[3 2 1];>>polyval(p,5)

produces, ans =86

and, >>roots(p)

will evaluate the roots of the polynomial, p.

II. Further Use

9. M-Files (Script Files)

• If a sequence of commands is to be used frequently, rather than re-typing, they can be stored in an 'm-file' - a file with an extension '.m'. This file can be created with any text editor of your choice and saved inany given working folder. From within MATLAB it is also possible to editan m file by:

>>edit filename

A new m-file can be created by omitting thefilename

and then selecting'File/Save As' under the editor.

Note: (i) When saving, a full MS-DOS path should be given (ii) any usergenerated m-files should be saved in a user defined folder, to avoidclutter in the MATLAB folders. For example, to calculate the hypotenuse of a right angled triangle (%indicates a comment line), create a file 'hypot.m' containing:

% calculate hypotenuse

asquared=b*b+c*ca=sqrt(asquared)

By typing hypot, after entering values for b and c, the result would beobtained. Note that the '.m' extension should not be entered.

10. Graphics

Using any of the graphics commands will generate a graphical output, ina graphics window.

e.g. >> plot(x,y)

Intro-Matlab&Simulink.doc

5

Page 6: Intro Matlab&Simulink

8/3/2019 Intro Matlab&Simulink

http://slidepdf.com/reader/full/intro-matlabsimulink 6/12

will plot the array, x, against y. Axes can be labelled with 'xlabel' etc.

11. Saving Variables

• Terminating a MATLAB session causes all variables to be lost. They can

be saved, in the current directory by:

>>save filename

 If 'filename' is omitted, the default file 'matlab.mat' is used.

• To renew variables, enter:>>load filename

Entering 'load' without a filename would cause the default file variables in'matlab.mat' to be loaded.

12. Hard Copy

• M-files and workspace files (e.g. matlab.mat) are normal text files andcan be printed out, from within the Windows environment, in the usualway.

• To obtain a graphics copy, from within the Windows environment, theeasiest way is toclick on File/Print from the graphics window.

___________________________________________

Intro-Matlab&Simulink.doc

6

Page 7: Intro Matlab&Simulink

8/3/2019 Intro Matlab&Simulink

http://slidepdf.com/reader/full/intro-matlabsimulink 7/12

Introduction to the Simulation Package: SIMULINK 

Calling SIMULINK and Building a Simple Model

SIMULINK is called from MATLAB. Start SIMULINK by either clicking on theSIMULINK icon on the MATLAB tool bar or entering simulink at the MATLABprompt.

 Two new windows will appear on the screen. The first is the SIMULINK block library (see Fig A1), the second is an empty model window, nameduntitled , in which a SIMULINK model can be built.

Fig. A1 SIMULINK Block Library Window

 The simple model to be built is one that solves the differential equation,

sin( )x t= with initial conditions x(0) = 0.

It should be noted that, although models are often written in differentialequation form, the SIMULINK model form uses the corresponding integralform. That is:

x t dt or xs

t= =∫ sin( ) , sin( )1

where, 1/s , represents an integration.

Double click on the sources icon in the SIMULINK block library, to open

Intro-Matlab&Simulink.doc

7

Page 8: Intro Matlab&Simulink

8/3/2019 Intro Matlab&Simulink

http://slidepdf.com/reader/full/intro-matlabsimulink 8/12

the Sources block library (Fig. A2).

Fig A2 Sources Block Library

Drag the sine wave block from the sources block library to the modelwindow, positioning as shown in Fig A3.

Intro-Matlab&Simulink.doc

8

Page 9: Intro Matlab&Simulink

8/3/2019 Intro Matlab&Simulink

http://slidepdf.com/reader/full/intro-matlabsimulink 9/12

Fig A3 Building the Model

A copy of the block is placed in the model window. Open the Linear Blocklibrary and drag an Integrator block to the model window. Open the SinksBlock library and drag a Scope block to the model window . The modelneeds to be completed by connecting the signal lines of the blocks. Placethe cursor on the output port of the Sine Wave block. The cursor changesto a cross-hair when on the port. Drag the output port of to the inputport of the Integrator block. (Fig. A4). The signal line has an arrow headindicating the direction of signal flow.

Intro-Matlab&Simulink.doc

9

Page 10: Intro Matlab&Simulink

8/3/2019 Intro Matlab&Simulink

http://slidepdf.com/reader/full/intro-matlabsimulink 10/12

Fig A4 Model with Connection

Draw another signal line from the output port of the Integrator block tothe input port of the Scope. This completes the model (Fig. A5).

Fig A5 Complete Model

Double click on the Scope block to open a Scope window. Select

Simulation/Start from the menu bar in the model window. Thesimulation will execute (Fig. A6).

Intro-Matlab&Simulink.doc

10

Page 11: Intro Matlab&Simulink

8/3/2019 Intro Matlab&Simulink

http://slidepdf.com/reader/full/intro-matlabsimulink 11/12

Fig A6 Scope Display

Additional Features of SIMULINK 

• The physical size of the SIMULINK block in the model can be increasedby dragging.

• The SIMULINK model can be printed by selecting file/print from themodel pull down menu.

• When using a transfer function block (obtained after double clicking onthe Linear block icon in the SIMULINK block library and the draggingthe transfer function block to the model):

- double click on the block to change elements- parameters in the transfer function can be entered as MATLAB

variables and their values set/changed from within MATLAB.

• To branch from a signal flow line (useful for feedback loops, etc.), the'control' key should be held down when dragging the cursor from thestart of the desired signal branch.

• Gain block values can be changed by double clicking the block. Again,it may be moreconvenient to enter a gain value as a MATLAB variable and set its valuefrom within MATLAB.

• The Scope output cannot be printed directly. Hard copies of graphicaloutput can be obtained by: (i) replacing the scope by an 'XY Plot',from "sinks", and adding a 'clock' input, from "sources", as the firstinput (X axis) or, (ii) saving the response output values in the scopeWorkspace (click on the properties icon on the Scope tool bar) and then

plot using 'plot' in MATLAB. ______________________________________________________ 

Intro-Matlab&Simulink.doc

11

Page 12: Intro Matlab&Simulink

8/3/2019 Intro Matlab&Simulink

http://slidepdf.com/reader/full/intro-matlabsimulink 12/12

 J.E.Ellis

Intro-Matlab&Simulink.doc

12