matlab - tutorialkasim/.../matlab/...matlabtutorial.pdf · • “matlab is a high-level technical...

Post on 18-Jan-2021

13 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Simon Fraser University

ENSC 383, 2006-2

MATLAB Tutorial

rev: May 10, 2006

P. 2Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB

• Matlab = Matrix Laboratory• Originally a user interface for numerical linear algebra

routines (Lapak/Linpak) • Commercialized 1984 by The Mathworks• Since then heavily extended (defacto-standard)

Alternatives Complements

• Matrix-X Maple (symbolic)Octave (free; GNU) Mathematica (symbolic)Lyme (free; Palm)

P. 3Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

• “MATLAB is a high-level technical computing language and interactive environment for algorithm development, data visualization, data analysis, and numerical computation.

• Using MATLAB, you can solve technical computing problems faster than with traditional programming languages, such as C, C++, and Fortran.”

MATLAB

P. 4Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB

• The MATLAB environment is command oriented somewhat like UNIX. A prompt appears on the screen and a MATLAB statement can be entered. When the <ENTER> key is pressed, the statement is executed, and another prompt appears.

• If a statement is terminated with a semicolon ( ; ), no results will be displayed. Otherwise results will appear before the next prompt.

• The following slide is the text from a MATLAB screen.

P. 5Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB

To get started, type one of these commands: helpwin, helpdesk, or demo

» a=5;» b=a/2

b =

2.5000

»

P. 6Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB Variable Names

• Variable names ARE case sensitive

• Variable names can contain up to 63 characters (as of MATLAB 6.5 and newer)

• Variable names must start with a letter followed by letters, digits, and underscores.

P. 7Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB Special Variables

ans Default variable name for resultspi Value of πeps Smallest incremental numberinf InfinityNaN Not a number e.g. 0/0i and j i = j = square root of -1realmin The smallest usable positive real numberrealmax The largest usable positive real number

P. 8Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB Math & Assignment Operators

Power ^ or .^ a^b or a.^bMultiplication * or .* a*b or a.*bDivision / or ./ a/b or a./b

or \ or .\ b\a or b.\aNOTE: 56/8 = 8\56

- (unary) + (unary)Addition + a + bSubtraction - a - bAssignment = a = b (assign b to a)

P. 9Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

Other MATLAB symbols

>> prompt. . . continue statement on next line, separate statements and data% start comment which ends at end of line; (1) suppress output

(2) used as a row separator in a matrix: specify range

P. 10Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB Help System

• Search for appropriate function• >> lookfor keyword

• Rapid help with syntax and function definition • >> help function

• >> helpwin function

• An advanced hyperlinked help system is launched by• >> helpdesk

• Complete manuals as PDF files

P. 11Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

• In Matlab, a polynomial is represented by a vector. To create a polynomial in Matlab, simply enter each coefficient of the polynomial into the vector in descending order.

• x = [1 3 -15 -2 9]; y = [1 0 0 0 1] ;• roots([1 3 -15 -2 9]); z = polyval([1 0 0 0 1],2);

92153 234 +−−+ ssss 14 +s

MATLAB - Polynomials

P. 12Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB - Polynomials

• Multiply • x = [1 2]; y = [1 4 8]; • z = conv(x,y)

z = 1 6 16 16• Divide• [xx, R] = deconv(z,y)

xx = 1 2 R = 0 0 0 0

P. 13Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB Matrices

• MATLAB treats all variables as matrices. For our purposes a matrix can be thought of as an array, in fact, that is how it is stored.

• Vectors are special forms of matrices and contain only one row OR one column.

• Scalars are matrices with only one row AND one column

P. 14Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB Matrices

• A matrix with only one row AND one column is a scalar. A scalar can be created in MATLAB as follows:

» a_value=23

a_value =

23

P. 15Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB Matrices

• A matrix with only one row is called a row vector. A row vector can be created in MATLAB as follows (note the commas):

» rowvec = [12 , 14 , 63]

rowvec =

12 14 63

P. 16Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB Matrices

• A matrix with only one column is called a column vector. A column vector can be created in MATLAB as follows (note the semicolons):

» colvec = [13 ; 45 ; -2]

colvec =

1345-2

P. 17Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB Matrices

• Entering matrices into Matlab is the same as entering a vector, except each row of elements is separated by a semicolon (;) or a return:

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

A =

1 2 34 5 67 8 9

P. 18Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB Matrices

• Matrices in Matlab can be manipulated in many ways:• G = E .* F, E^3, E.^3, X = inv(E), eig(E), p = poly(E)

» C = A' C = 1 5 9

2 6 103 7 11 4 8 12

P. 19Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB Matrices• A column vector can be

extracted from a matrix. As an example we create a matrix below:

» matrix=[1,2,3;4,5,6;7,8,9]

matrix =

1 2 34 5 67 8 9

• Here we extract column 2 of the matrix and make a column vector:

» col_two=matrix( : , 2)

col_two =

258

P. 20Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB Matrices• A row vector can be

extracted from a matrix. As an example we create a matrix below:

» matrix=[1,2,3;4,5,6;7,8,9]

matrix =

1 2 34 5 67 8 9

• Here we extract row 2 of the matrix and make a row vector. Note that the 2:2 specifies the second row and the 1:3 specifies which columns of the row.

» rowvec=matrix(2 : 2 , 1 : 3)

rowvec =

4 5 6

P. 21Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

Scalar - Matrix Addition

» a=3;» b=[1, 2, 3;4, 5, 6]b =

1 2 34 5 6

» c= b+a % Add a to each element of bc =

4 5 67 8 9

P. 22Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

Scalar - Matrix Subtraction

» a=3;» b=[1, 2, 3;4, 5, 6]b =

1 2 34 5 6

» c = b - a %Subtract a from each element of bc =

-2 -1 01 2 3

P. 23Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

Scalar - Matrix Multiplication

» a=3;» b=[1, 2, 3; 4, 5, 6]b =

1 2 34 5 6

» c = a * b % Multiply each element of b by ac =

3 6 912 15 18

P. 24Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

Scalar - Matrix Division

» a=3;» b=[1, 2, 3; 4, 5, 6]b =

1 2 34 5 6

» c = b / a % Divide each element of b by ac =

0.3333 0.6667 1.00001.3333 1.6667 2.0000

P. 25Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

Extracting a Sub-Matrix

• A portion of a matrix can be extracted and stored in a smaller matrix by specifying the names of both matrices and the rows and columns to extract. The syntax is:

sub_matrix = matrix ( r1 : r2 , c1 : c2 ) ;

where r1 and r2 specify the beginning and ending rows and c1 and c2 specify the beginning and ending columns to be extracted to make the new matrix.

P. 26Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

Using M/MAT-files in Matlab

• There is a built-in editor for m-files; choose "New M-file" from the File menu. You can also use any other editor you like (but be sure to save the files in text format and load them when you start Matlab).

• MAT: SAVE workspace variables on disk.• Mac, Windows, Unix.

P. 27Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

Reading Data from files• MATLAB supports reading an entire file and creating a

matrix of the data with one statement.

>> load mydata.dat; % loads file into matrix.% The matrix may be a scalar, a vector, or a % matrix with multiple rows and columns. The% matrix will be named mydata.>> size (mydata) % size will return the number

% of rows and number of% columns in the matrix

>> length (myvector) % length will return the total% no. of elements in myvector

P. 28Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

Plotting with MATLAB

• MATLAB will plot one vector vs. another. The first one will be treated as the abscissa (or x) vector and the second as the ordinate (or y) vector. The vectors have to be the same length.

• MATLAB will also plot a vector vs. its own index. The index will be treated as the abscissa vector. Given a vector “time” and a vector “dist” we could say:

>> plot (time, dist) % plotting versus time >> plot (dist) % plotting versus index

P. 29Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

Plotting with MATLAB

• There are commands in MATLAB to "annotate" a plot to put on axis labels, titles, and legends. For example:

>> % To put a label on the axes we would use:>> xlabel ('X-axis label')>> ylabel ('Y-axis label')

>> % To put a title on the plot, we would use:>> title ('Title of my plot')

P. 30Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

Plotting with MATLAB

• Vectors may be extracted from matrices. Normally, we wish to plot one column vs. another. If we have a matrix “mydata” with two columns, we can obtain the columns as a vectors with the assignments as follows:

>> first_vector = mydata ( : , 1) ; % First column>> second_vector = mydata ( : , 2) ; % Second one>>% and we can plot the data>> plot ( first_vector , second_vector )

P. 31Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

Some Useful MATLAB commands

• who List known variables• whos List known variables plus their size• help Ex: >> help sqrt Help on using sqrt• lookfor Ex: >> lookfor sqrt Search for

keyword sqrt in m-files• what Ex:>> what a: List MATLAB files in a:• clear Clear all variables from work space• clear x y Clear variables x and y from work space• clc Clear the command window

P. 32Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

Some Useful MATLAB commands

• what List all m-files in current directory• dir List all files in current directory• ls Same as dir• type test Display test.m in command window• delete test Delete test.m• cd a: Change directory to a:• chdir a: Same as cd• pwd Show current directory• which test Display current directory path to

test.m

P. 33Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB Relational Operators

• MATLAB supports six relational operators.

Less Than <Less Than or Equal <=Greater Than >Greater Than or Equal >=Equal To ==Not Equal To ~=

P. 34Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB Logical Operators

• MATLAB supports three logical operators.

not ~ % highest precedenceand & % equal precedence with oror | % equal precedence with and

P. 35Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB Logical Functions

• MATLAB also supports some logical functions.xor (exclusive or) Ex: xor (a, b)

Where a and b are logical expressions. The xoroperator evaluates to true if and only if one expression is true and the other is false. True is returned as 1, false as 0.

any (x) returns 1 if any element of x is nonzeroall (x) returns 1 if all elements of x are nonzeroisnan (x) returns 1 at each NaN in xisinf (x) returns 1 at each infinity in xfinite (x) returns 1 at each finite value in x

P. 36Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB Display formats

• MATLAB supports 8 formats for outputting numerical results.

format long 16 digitsformat short e 5 digits plus exponentformat long e 16 digits plus exponentformat hex hexadecimalformat bank two decimal digitsformat + positive, negative or zeroformat rat rational number (215/6)format short default display

P. 37Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

Matlab Selection Structures

• An if - elseif - else structure in MATLAB.Note that elseif is one word.

if expression1 % is true% execute these commands

elseif expression2 % is true% execute these commands

else % the default% execute these commands

end

P. 38Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB Repetition Structures

• A for loop in MATLAB for x = arrayfor x = 1: 0.5 : 10

% execute these commandsend

• A while loop in MATLAB while expressionwhile x <= 10

% execute these commandsend

P. 39Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB Toolbox

• MATLAB has a number of add-on software modules, called toolbox , that perform more specialized computations.

Signal & Image ProcessingSignal Processing- Image Processing Communications - System Identification -Wavelet Filter Design

Control DesignControl System - Fuzzy Logic - Robust Control - µ-Analysis and Synthesis - LMI Control - Model Predictive Control Model-Based Calibration

More than 60 toolboxes!More than 60 toolboxes!

P. 40Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB Toolbox

MATLAB has many toolboxes: • Control toolbox is one of the important toolbox in

MATLAB. • RLC Circuit Response, • Gain and Phase Margins, • Notch Filter Discrete, • PID and ...

P. 41Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

Some Functions

• gensig Generate test input signals for lsim• impulse Impulse response • initial Free response to initial condition • ltiview LTI system viewer • step Step response• lsim• bode• rlocus• nyquist……

P. 42Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

LTIVIEW

• ltiview(PLOTTYPE,SYS1,SYS2,...,SYSN) further specifies which responses to plot in the LTI Viewer.

1) ‘step’ Step response2) ‘impulse’ Impulse response3) ‘bode’ Bode diagram4) ‘bodemag’ Bode Magnitude diagram5) ‘nyquist’ Nyquist plot6) ‘nichols’ Nichols plot7) ‘sigma’ Singular value plot8) ‘pzmap’ Pole/Zero map

For example,ltiview({'step';'bode'},sys1,sys2)

P. 43Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB Demo

• Demonstrations are invaluable since they give an indication of the MATLAB capabilities.

• A comprehensive set are available by typing the command >>demo in MATLAB prompt.

P. 45Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB – System Response

• Impulse Response

• Step Response

– The step response is the output signal that results from a step input, i.e., u(t) is zero for negative values of t and equal to one for positive values of t. The impulse and step responses together are called the model's transient response

• Frequency Response

• Zeros and Poles

* Step* Impulse* Bode* Nyquist* Nichols* Sigma* Pole-Zero* Root Locus

P. 46Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

MATLAB – System Response Examples

>>num = [ 1 ]; % Numerator

>>den = [ 1 2 10 ]; % Denominator

>>H = tf(num,den)>>step(H)

P. 47Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

Sample - RLC Band Stop Filter

• Consider the circuit below:

RL

C

++

_

_

VOVi=)(sGv

The transfer function for VO/Vi can be expressed as follows:

LCs

LRs

LCs

sGv 1

1

)(2

2

++

+=

P. 48Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

RLC Band Stop Filter

This is of the form of a band stop filter. We see we have complex zeros on the jw axis located

LCj 1

±

From the characteristic equation we see we have two poles. The poles an essentially be placed anywhere in the left half of the s-plane. We see that they will be to the left of the zeros on the jw axis.

We now consider an example on how to use this information.

P. 49Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

RLC Band Stop Filter

The transfer function is:

3000003100300000

2

2

+++

sss

We now write a Matlab program to simulate this transfer function.

Design a band stop filter with a center frequency of 632.5 rad/sec and having poles at 100 rad/sec and 3000 rad/sec.

P. 50Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

RLC Band Stop Filter

num = [1 0 300000];

den = [1 3100 300000];

w = 1 : 5 : 10000;

bode(num,den,w)

P. 51Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

Where Do I Go From Here?• The Language of Technical Computing – the official website

– http://www.mathworks.com/products/matlab• A Partial List of On-Line Matlab Tutorials and Matlab Books

– http://www.duke.edu/~hpgavin/matlab.html• Getting started with Matlab

– http://www.engr.iupui.edu/ee/courses/matlab/tutorial_start.htm• A quick reference to some of the key features of Matlab

– http://science.ntu.ac.uk/msor/ccb/matlab.html#MATLAB• Matlab tutorial, with lots of links to other tutorials

– http://www.glue.umd.edu/~nsw/ench250/matlab.htm• Control Tutorial for Matlab

– http://www.engin.umich.edu/group/ctm/home.text.html• A Practical Introduction to Matlab

– http://www.math.mtu.edu/~msgocken/intro/intro.html• Matlab Tutorial Information from UNH

– http://spicerack.sr.unh.edu/~mathadm/tutorial/software/matlab/

P. 52Guangqing JIA, William A. GRUVERSimon Fraser University

ENSC 383, 2006-2

The END!

top related