78
MATLAB - Advanced Workshop Overview Working in MATLAB Complex Arithmetic Logic & Arrays Polynomials & Inline Functions Systems of Equations Eigenvalues/Eigenvectors Advanced Graphing Numerical Integration Discrete-time Signals & Convolution Transfer Functions User-defined Functions Using the Symbolic Toobox and Simulink Useful GUI‟s 3/5/2011 Comprehensive MATLAB 1

MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

  • Upload
    others

  • View
    13

  • Download
    0

Embed Size (px)

Citation preview

Page 1: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

MATLAB - Advanced Workshop

Overview

• Working in MATLAB

• Complex Arithmetic

• Logic & Arrays

• Polynomials & Inline

Functions

• Systems of Equations

• Eigenvalues/Eigenvectors

• Advanced Graphing

• Numerical Integration

• Discrete-time Signals &

Convolution

• Transfer Functions

• User-defined Functions

• Using the Symbolic Toobox

and Simulink

• Useful GUI‟s

3/5/2011 Comprehensive MATLAB 1

Page 2: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 2

Keeping Track of Your Work

• To make a file of your current workspace efforts, the syntax is:

>> diary filename

• Say we want to record our work in a file called Joes_practice; type

>> diary Joes_practice

• The default location of the file is in the Work folder (inside of your

Matlab folder), which is where your script-M files will also be stored.

• You can change the default location by typing the path to your desired

location in front of the filename:

>> diary path/filename

• The diary can be turned on and off while you work with the

commands: diary on and diary off

Page 3: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 3

The MATLAB Desktop

• Matlab usually opens up with (at least) three windows

showing:

– the Command Window,

– the Workspace Window, and

– the Command History Window.

• If these 3 windows are not visible when you open

MATLAB, go to the top menu bar and select:

Desktop Desktop Layout Default

• Note that these 3 windows can be resized by dragging the

edges, and they can be closed using the x-box in the top

right corner of each window.

Page 4: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 4

Getting Around in the Workspace

• If you make a mistake,

– Press enter to get a new prompt, and type the desired command again; or,

– Use the up-arrow ( ) to move up to a previous entry, and the left and right arrows ( , ) to move to the part of line you want to edit.

– Use the delete key to remove a character in front of the cursor, or the backspace key to remove a character behind the cursor.

– Use the escape key to clear an entire line

– Use Ctrl+C to stop an operation and get a new command line prompt

Page 5: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 5

Getting Around in the Workspace, cont.

• Use a semi-colon (;) at the end of a line or command to

suppress the display of the result on the screen

• Put several commands on one line, separating them with

commas (or semi-colons to suppress the display of the

result on the screen)

• Use spacing to make your code more readable

• Use an ellipsis (…) to continue a long line of code to the

next line

Page 6: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 6

Keeping Track of Variables in MATLAB

• The who command will display a list of all defined variables. (whos will

also display the size of each variable)

• The size function will give the number of rows & columns of a matrix (as

in size(A))

• Typing the name of a variable and pressing enter will display the current

value of the variable, or an error message if no such variable exists.

• The clc command clears the command window, but leaves the value of

any variables unchanged.

• clear var1 var2 clears the value of variables var1 and var2 from

memory. (O.K. to use * for wild card, as in clear a*)

• The clear command clears the value of all variables from memory.*

: MATLAB retains the value of any variables you set during a given

work-session until you quit MATLAB or explicitly clear the variables.

Page 7: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 7

Controlling the Numeric Format of the Display

• All computations in MATLAB are done in double precision (8 bytes).

• Some variations on the FORMAT command are listed below:

– FORMAT Default. Same as SHORT.

– FORMAT SHORT Scaled fixed point format with 5 digits.

– FORMAT LONG Scaled fixed point format with 15 digits.

– FORMAT SHORT E Floating point format with 5 digits.

– FORMAT LONG E Floating point format with 15 digits.

– FORMAT SHORT G Best of fixed or floating point format with 5 digits.

– FORMAT LONG G Best of fixed or floating point format with 15 digits.

– FORMAT SHORT ENG 5 sign. digits, and power is a multiple of 3

– FORMAT LONG ENG 16 sign. digits, and power is multiple of 3

Page 8: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 8

Controlling the Numeric Format of the Display

– FORMAT BANK Format for dollars & cents

– FORMAT HEX Hexadecimal display

• Practice: Type in the vectors x = [7/3 1.3579e-6 pi], and y = [7/3 1.3579e-6 pi 2222.34], followed by the various format commands above. (Ask for the values of x and y after typing each format.)

Page 9: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 9

Getting Help

• To find help when you don‟t know the name of the function you want, use the

lookfor command, with syntax:

lookfor keyword

– Example: say I want to do make a graph, but I don‟t know how; type

lookfor graph

– MATLAB will return with several commands/functions that are related to

graphing.

• If you know the name of a particular function, but need help with the syntax, use

the help command, with syntax:

help function

– Example: say I want to make a graph using the plot function, but I don‟t

remember the syntax or how the function works; type

help plot

– MATLAB will return with the syntax and a description of the function.

Page 10: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 10

Getting Help, cont.‟

• If you know the name of a particular function you want, but need help with the syntax and/or thorough documentation about the mathematical algorithm employed, use the doc command, with syntax:

>> doc function

– Example: continuing with the graphing example from the previous page, to get more information and examples about using the plotfunction, type

>> doc plot

– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough description of the function.

____________

Note that this will only work if you included documentation when MATLAB was installed on your computer, or if you have the documentation CD in the CD drive.

Page 11: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 11

Built-in Functions(too numerous for exhaustive list)

sqrt - square root

exp - exponential

(e.g., ex = exp(x))

log - natural log (base e)

log10 - log base 10

log2 - log base 2

sin - sine

sinh - hyperbolic sine

asin - inverse sine

asinh - inverse hyperbolic sine

cos - cosine

cosh - hyperbolic cosine

acos - inverse cosine

acosh - inverse hyperbolic cosine

tan - tangent

cot - cotangent

sec - secant

abs - absolute value

conj - complex conjugate

fix - round towards 0

floor - round towards (-inf)

ceil - round towards (inf)

size - dimensions of an array

det - determinant of a matrix

Trig functions require argument to be given in radians;

angular measure answers are also given in radians.

Page 12: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 12

More Built-in Functions – EE Related

sind - sine of angle given in degrees

asind - inverse sine, answer given in degrees

cosd - cosine of angle given in degrees

acosd - inverse cosine, answer given in degrees

Similar functions

exist for tan, sec,

csc

mag2dB - converts magnitude data to decibels: ydb = 20 log10(y)

dB2mag - converts decibel data to linear magnitude: y = 10.^(ydb/20)

pol2cart - converts from polar form to Cartesian (rect.) form

- (or from cylindrical to Cartesian for 3D case)

cart2pol - converts numbers from Cartesian (rect.) form to polar form

- (or from Cartesian to cylindrical for 3D case)

Similarly: see cart2sph, sph2cart (for spherical Cartesian conversion)

and hex2dec, dec2hex (for hexadecimal binary conversion)

Page 13: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 13

More Built-in Functions – EE Related

\pi - gives character for pi: p

Example: >> xlabel(„x = 0 : \pi‟)

- provides an x-axis label on a graph: x = 0 : p

type - displays content of file

Example: type sind % displays code used to find sine of

% angle when angle is given in degrees

Matrix Functions: det, eig, inv, norm, rank, …

Special Matrices: diag, eye (identity matrix), toeplitz, pascal, …

Page 14: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 14

1. Calculate:

a. 234 - 4 b. 4p – 183 c. log(37) d. ln(37)

e. sin(1) f. cos(60) g. e2 h. tan-1(1/2)

i. log2(64) j. k.

2. Find the area of a circle with radius 5 inches.

3. Use the formulas V = I R (Ohm‟s Law) and P = V2/R to find the

voltage (V) across and power (P) dissipated by a resistor if the current

(I) through the resistor is 5 amps and the resistor value R is 100 ohms.

Exercise Set 1

Recall that (per mathematical convention) log means log base 10, or common log;

ln means log base e, or natural log – compare to the MATLAB definitions, p. 11.

Answers: 1a. 279,826.58 1b. –5,819.43 1c. 1.5682 1d. 3.6109

1e. 0.8415 1f. 0.5 1g. 7.3891 1h. 0.4636 1i. 6 1j. 2

1k. 0.707 2. 78.5398 sq. in. 3. V = 500 volts, P = 2500 Watts

13

5 32 2/1

Page 15: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 15

Complex Arithmetic

• Notation: write a + bi as is, without a multiplication sign (*) between the b and the i

• Use either i or j for the square root of (-1)

• +, -, *, and / are performed as with real numbers

• Example of a work session with complex arithmetic

>> x = 3 + 4i; y = 3 – 6i;

>> x + y

ans =

6 – 2i

>> x * y

ans =

33 – 6i

Page 16: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 16

Complex Arithmetic: Rectangular (Cartesian) and Polar Notation

• Use abs( ) to find the magnitude, and angle( ) to find the phase angle (in radians) of a complex number, as shown below:

>> x = 3 + 4i; w = abs(x); z = angle(x);

>> w, z

ans =

5

ans =

.9273

• You can also use the commands cart2pol (for changing cartesiancoordinates to polar coordinates) and pol2cart (for changing polar coordinates to cartesian coordinates, as shown below (answers not shown):

>> [theta, rho]=cart2pol(3, 4 )

>> [x1, y1] = pol2cart(.9273, 5)

Page 17: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 17

Logic & Relational Operations

(to get answers for true/false questions: T = 1, F = 0)

Operator Description Example

< Less than: returns a 1 for values < RHS A < 1 = [ 1 0 0]

< = Less than or equal to A <= 1 = [ 1 1 0]

> Greater than: returns a 1 for values > RHS B > 2 = [ 1 0 0]

> = Greater than or equal to A >= B = [0 0 1]

= = Equal to: returns a 1 for values : LHS = RHS A = = B = [0 0 0]

~ = Not equal to A ~ = B = [1 1 1]

& And (A<1) & (B>2) = [1 0 0]

| Or (A 1) | (B>2)= [1 1 0]

~ Not ~(A>B) = [1 1 0]

For examples, assume: A = [ 0 1 2 ]; B = [ 3 2 1 ];

LHS: left-hand side; RHS: right-hand side

Page 18: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 18

Linspace vs. Logspace Vectors

• To fill a vector with equally spaced components, use the function

linspace, requiring 3 arguments, with syntax:

linspace(1st_value, last_value, # of values)

• Example: To get 20 linearly-spaced points between 0 and 2 pi, type:

>> t = linspace(0, 2*pi, 20)

• If we want an array of points with logarithmic spacing, we use the

function logspace, requiring 3 arguments, with syntax:

logspace(1st_exponent on 10, last exponent on 10, # of values)

• Example: To get an array starting at 100 = 1, ending at 103 = 1000,

with 20 points, type:

>> t = logspace(0, 3, 20)

Page 19: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 19

More on Vectors and Matrices

• To find the determinant of the square matrix called mA as given below, try:

>> mA = [1 2 0; 4 5 6; 7 8 1]

>> det(mA)

• To find the rank of a matrix, say matrix mA above, type:

>> rank(mA)

Page 20: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 20

MATLAB Example: Same Problem, Regular Math:

>> a = [1 1; 2 2]

a = a =

1 1

2 2

>> a + 5 a + 5 = ????

ans = (not a legal matrix

6 6 operation)

7 7

22

11

MATLAB calls this scalar expansion, since it actually expands the

scalar addend to the required matrix size to make matrix addition

possible. Subtraction works the same way.

Page 21: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 21

Polynomials Represented by Vectors

• An array can also be used to define a polynomial, just by listing its coefficients, in decreasing order of the powers; e.g., the polynomial x3

+ 4x2 – 7 can be represented as [1 4 0 -7].

• To find the roots* of the above polynomial, type >> roots([1 4 0 -7])

• To find the polynomial with a given set of roots (say r1 = 2, r2 = 4, and r3 = 8), type

>> poly( [2, 4, 8 ] )

• To multiply two polynomials, say a(x) and b(x) where a(x) = x3+3x+7 and b(x) = x4 - 2x3 + 7x2 + 3x + 4, type

>> a = [1 0 3 7]; b = [1 -2 7 3 4];

>> c = conv(a,b)

* This is equivalent to finding the roots of the equation x3 + 4x2 – 7 = 0.

Page 22: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 22

Evaluating Polynomials and Other Functions

• Arbitrary functions can be defined as a string by setting the

RHS of the equation in quotes; e.g., for polynomial f1(x),

>> f1 = „x^3 – 10*x^2 + 16‟

• To evaluate the polynomial, say for x = 2, we type:

>> x = 2

>> eval(f1)

• Or, say f(x) = x3 – 10x2 + 16, and we want to evaluate f(x)

at x = 2; we could type

>> f = [1 –10 0 16];

>> polyval(f, 2)

Page 23: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 23

Inline Functions

• Another way to define a function is using the command :

inline(„formula‟)

• If y = e-x sin(5x), we can enter this formula into Matlab as:

>> y=inline(„exp(-x)*sin(5*x)‟)

• To graph this function we can type:

>>ezplot(y,[0,5])

• If we want to specify the y-axis, we can use:

>>ezplot(y, [0, 5, -1, 1])

Page 24: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 24

Inline Functions

• We can also use the inline function to find the roots of a function

• If we want to find the roots of y = e-x sin(5x), we enter:

>> y=inline(„exp(-x)*sin(5*x)‟)

>> fzero(y,0)

• The 0 argument gives the initial values for the search for roots. Try:

>>fzero(y,.5)

• It is useful to graph the function first so that you can find reasonable

initial values

Page 25: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 25

Systems of Equations: the Matrix View

• Consider the system of equations below, with 3 equations in 3

unknowns. We want to solve for x1, x2, and x3:

x1 + x2 + 3 x3 = -32x1 - 3x2 + 2 x3 = -8x1 + 2x2 - x3 = 7

• We pick off the coefficient matrix A, and the constant vector b, to get an equation of the form Ax = b, where

1 1 3 -3 x1

A = 2 -3 2 b = -8 x = x2

1 2 -1 7 x3

• To solve the equation Ax = b, for the vector x, we use: x = A-1 b.

• Enter the coefficient matrix A and the constant vector b; then type<< inv(A)*b

(Hopefully you‟ll get x1 = 1, x2 = 2, x3 = -2.)

Page 26: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 26

Overdetermined Systems of Equations(more equations than unknowns no exact solution, usually)

• Consider a system with 3 equations and only 2 unknowns; e.g., x1 + x2 = 32x1 - 3x2 = -4

x1 + 2x2 = 6

• We pick off the coefficient matrix A, and the constant vector b, to get an equation of the form Ax = b, where

1 1 3 x1

A = 2 -3 b = -4 x = x2

1 2 6

• To solve the equation Ax = b, for vector x, use left division: x = A \ b.

• Enter the coefficient matrix A and the constant vector b; then type<< A \ b

(Hopefully you‟ll get x1 = 1.2667 and x2 = 2.2. In general, the left division or backslash operator finds the least squares solution for overdetermined systems.)

Page 27: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 27

Underdetermined Systems of Equations(more unknowns than equations # of solutions, usually)

• Consider a system with only 2 equations and 3 unknowns; e.g.,

x1 + x2 + x3 = 3

x1 + 2x2 = 6

• We pick off the coefficient matrix A, and the constant vector b, to get an equation of the form Ax = b, where

1 1 1 3 x1

1 2 0 6 x2

x3

• To solve Ax = b, for vector x, again use left division: x = A \ b.

• Enter the coefficient matrix A and the constant vector b; then type<< A \ b

(Hopefully you‟ll get x1 = 0 = x3, and x2 = 3. In general, the left division or backslash operator finds one of infinitely many solutions for under-determined systems, using QR factorization.)

A = b = x =

Page 28: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 28

Eigenvalues and Eigenvectors

• Consider the matrix a = 1 2 0

4 5 6

7 8 1

• To find the eigenvalues of matrix a, enter matrix a and then type

>> eiga = eig(a)

• If you prefer to have the fractional form (rather than decimals), also

type:

>> rats(eiga)

• To put the eigenvalues in size order, from smallest to largest, also

type:

>> sort(eiga)

Page 29: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 29

Eigenvalues and Eigenvectors, cont.‟

• To find the characteristic polynomial for matrix a, type:

>> poly(a)

• Double-check: If we find the roots of the characteristic

polynomial, we should get the eigenvalues back again:

>> roots(poly(a))

• To find the eigenvectors and eigenvalues of matrix a, type

>> [V, D] = eig(a)

• Matrix V will contain the eigenvectors as columns; matrix D

will be a diagonal matrix with eigenvalues on the diagonal,

in order corresponding to that of the eigenvectors.

Page 30: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 30

Exercise Set 2

1. Find the sixth roots of unity: i.e., solve the equation x6 = 1.

2. Simplify:

a. (2 + 3j) * (1 –2j) b. (2 + 3j) / (1 – 2j)

c. j2 d. j27

3. Given the following matrices and vectors:

1 2 1 1 2 2

A = 0 3 2 B = 2 3 C = [1 2 3] D = 1

2 1 1 3 0 2

a. find A*B b. find A-1*B c. find C*D

4. Solve the system of equations for x1, x2, and x3:

2x1 + 3x2 = 2x1 + x2 + x3 = 4

3x1 + 2x2 + 3x3 = 12

Some Answers: 1. 1, -.5 .866i, .5 .866i 2a. 8-j 2b. -.8 +1.4i 2c. –1 2d. –j 3a. [8 8; 12 9; 7 7] 3c. 10 4. x1 = 1, x2 = 0, x3 = 3

Page 31: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 31

Graphs

- Optional Refinements -

• We can change the line color, the plot symbols, and line type (solid, dotted, or dashed), in graphs, using a character string (set off with single quotes) made from one entry from any or all of the sets below:

Colors: {y (yellow), m (magenta), c (cyan), r (red), g (green),

b (blue), w (white), k (black) }

Plot symbols: { . , o, x , + , * , s (square), d (diamond), v (triangle) }

Line types: { - (solid), : (dotted), -- (dashed) }

• Example: Plotting some s(t), with a red dashed line, using diamondsfor plot symbols (to mark the data points):

>> plot( t , s , „r d - -‟)

Page 32: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 32

Graphs, cont.

- More Practice -

• Example: To graph x(t) = t2, for t [0, 3], using blue circles to make the data points, and connecting the points with a dotted red line, try graphing x(t) once for the line and once for the data points:

>> t = [ 0 : .2 : 3]; x = t .^ 2;

>> plot(t, x, „bo‟, t, x, „r : ‟)

• Use the Insert menu in the graph window to add axis labels and a title.

• Example: To graph x(t) = t2 and y(t) = 2t in two separate windows, we type the following:

>> t = [ 0 : .2 : 3]; x = t .^ 2; y = 2*t;

>> plot(t, x), figure, plot(t, y)

• Note that the figure command creates a new window for the second plot; without it, the second plot would overwrite the first plot.

Page 33: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 33

Graphs, cont.‟

- Turning Functions On and Off -

• Logic functions can be used as switches, to turn functions on and off.

• Example: say we want to graph sin(4t) from 0 to 10 pi, but switch it off

(i.e., graph 0) between 2 pi and 4 pi.

>> t = linspace(0, 10*pi, 1000);

>> sw_off = (t > 2*pi) & (t < 4*pi); % 1‟s on (2pi, 4pi), 0 else

>> sw_on = ~ sw_off; % 0‟s on (2pi,4pi), 1 else

>> y = sin(4*t) .* sw_on; plot(t, y)

Page 34: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 34

Graphs, cont.

- Split –Domain (or Discontinuous) Functions -

• Say we want to plot the function

cos(2000pt), 0 < t 2 ms, 4 ms < t 8 ms

y = cos(4000pt), 2 ms < t 4 ms, 8 ms < t 10 ms

• One approach: concatenate vectors, as follows:

>> t1 = linspace(0, .002, 100); y1 = cos(2000*pi*t1);

>> t2 = linspace(.002, .004, 100); y2 = cos(4000*pi*t2);

>> t3 = linspace(.004,.008, 200); y3 = cos(2000*pi*t3);

>> t4 = linspace(.008, .010, 100); y4 = cos(4000*pi*t4);

>> t = [t1 t2 t3 t4]; y = [y1 y2 y3 y4];

>> plot(t, y)

• Use the Insert menu at the top of the figure window to add axis labels and a graph title.

Page 35: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 35

Graphs, cont.

- Split –Domain (or Discontinuous) Functions -

• Example from the previous page/Alternate approach - make the two different functions for the cosines at different frequencies; use logic functions as switches to multiply by one where the functions belong and multiply by zero where the functions don‟t belong:

>> t = linspace(0, .010, 1000);

>> x = (t <= .002) | ( (.004 < t) & (t <=.008) ); % switch 1

>> y = t & ~x; % switch 2

>> x = x .* cos(2000*pi*t);

>> y = y .* cos(4000*pi*t);

>> z = x + y; plot( t, z)

• Again, use the Insert menu at the top of the figure window to add axis labels and a graph title.

Page 36: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 36

Graphs, cont.‟

- Histograms -

• The function hist(y) creates a histogram of the values in the vector y,

using 10 equally-spaced bins ranging from the minimum to the

maximum values in y. Example:

>> y = randn (1000,1); % vector of 1000 Gaussian variates

>> % with mean 0, variance 1

>> hist(y) % to get a 10-bin histogram

Page 37: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 37

Graphs, cont.‟

- Histograms -

• Add a second argument to the histogram function to set the number of

bins; say, in the previous example, we wanted 30 bins. We would type:

>> y = randn (1000,1); % vector of 1000 Gaussian variates

>> % with mean 0, variance 1

>> hist(y,30) % to get a 30-bin histogram

Page 38: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 38

Graphing 3-dimensional Functions

- Gaussian Probability Density Function Example -

• Say we want to plot the probability density function of two independent

Gaussian random variables, x and y, each with mean zero and variance 1:

z = f(x,y) =

• We use the command meshgrid to set up the domain in the x-y plane;

then we define the function z in terms of x and y, and use the command

mesh to generate the 3-D surface plot:

>> [x, y] = meshgrid(-3: .05 : 3, -3 : .05 : 3); % x and y from –3

>> % to 3, in steps of .05

>> z = (1/(2*pi)) * exp((x.^2 + y.^2)/(-2)); % defines Gaussian

>> mesh(z); % generates surface plot

2exp

2

1 22 yx

p

Page 39: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 39

3D Graphing

• There are many types of graphing functions in Matlab. Try:

>> z=inline(„cos(x).*cos(y).*exp(-sqrt(x.^2

+ y.^2)/4)‟);

>> ezsurf(z,[-5, 5, -5, 5])

-5

0

5

-5

0

5-0.5

0

0.5

x

cos(x) cos(y) exp(-sqrt(x2 + y

2)/4)

y

Page 40: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 40

Data Visualization- Assigning Colors to Numbers -

• Enter the row vector A = [0 10 20 30 40 50 60 70].

• Type the line

>> image(A)

• Expected result:

Page 41: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 41

Data Visualization- Assigning Colors to Numbers -

• Try the same image command on the matrix

706560

504030

20100

B

Page 42: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 42

Exercise Set 3

1. Plot: y(t) = t3 and z(t) = , for 0 t 2,

on a single graph with a grid. Use enough points so that

the curve is smooth. Label both curves and the x-axis,

and title the graph: “Exercise 3-1: Your name”. Make the

plot for z and dashed line, and the plot for y a solid line.

2. Plot s(t) = t3 – 6t2 + 6, for 0 t 4. Label both axes, t and

s. Title the graph: “Exercise 3-2: Your name”. The graph

should have a grid and be a smooth curve.

3 t

Page 43: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 43

Numerical Integration

• Using the trapezoidal rule, the syntax for integrating a function y(x)

with respect to the variable x is:

>> trapz(x,y)

• Suppose, for example, that we want to integrate the function y =

cos(x), as x goes from 0 to pi:

• The MATLAB code for the integral above is:

>> x = [ 0 : .01 : pi] ;

>> y = cos(x);

>> trapz(x,y)

0)sin()cos(0 0

p p

xdxx

Note: Your answer will “improve” if you take smaller steps in the x vector.

Page 44: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 44

Numerical Integration, continued

• Using “recursive adaptive Simpson quadrature “ technique to

approximate the integral of scalar-valued function FUN from A to B to

within an error of 1.e-6:

>> quad(FUN, A, B)

• Suppose, for example, that we want to integrate the function y =

exp(sin(x)), as x goes from 0 to 1:

• The MATLAB code for the integral above is:

>> quad(„exp(sin(x))‟, 0, 1)

ans =

1.6319

1

0

dx))xexp(sin(

Page 45: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 45

Discrete-time Convolution and Graphs

• Say we want to convolve x = [1 1 1 1 1 1] with itself.

• We will use the index n for the sequence of x values:

>> n = [0 : 5]

>> x = ones(1, 6)

• The command for convolving two sequences or vectors a and b is conv(a,b); since we want to convolve x with itself, type:

>> z = conv(x, x);

• To plot a discrete function (say z as a function of n1), the command is stem(n1,z); however, we need to tell Matlab where the convolution answer should be plotted (for n1 going from 0 to 10); thus, type

>> n1 = [0:10]; % sets domain for convolution answer

>> stem(n1,z) % makes discrete graph of z(n1)

x0

Page 46: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 46

Complex Discrete-time Signals

• Consider the discrete-time function x[n] = ej(p/8)n, on 0 n 16. Since this is complex-valued, we usually plot the magnitude and phase of the signal separately. Try the following code:

>> n = [0:16]; x = exp[j*(pi/8)*n];

>> y1 = abs(x); y2 = angle(x); % abs = mag, angle = phase

>> stem(n, y1)

>> stem(n, y2) % note phase angle is in radians

• Alternatively, we could plot the real and imaginary parts of the signal. Try the following code:

>> y3 = real(x); y4 = imag(x);

>> stem(n, y3)

>> stem(n, y4)

>> plot(y3, y4)

Page 47: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 47

• Transfer Function Model:

• Equivalent Differential Equation:

• Form vectors a (with N+1 elements) and b (with M+1

elements) with coefficients an and bm respectively, in

descending order of indices (or powers)

011

1

011

1

)()()(

)()()()(

ajajaja

bjbjbjbjH

NN

NN

MM

MM

Frequency Response Plots

M

mm

m

m

N

nn

n

ndt

txdb

dt

tyda

00

)()(

Page 48: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 48

Frequency Response Plots

• Say we have the system transfer function (or equivalent differential equation)

• Code to generate the frequency response (magnitude and phase):

>> a = [1 4]; b = 5; freqs(b,a)

• Note that the default is logarithmic spacing on the horizontal scale. To change to linear spacing, go to the menu bar on the plot, and select Edit Axis Properties

• We can also specify a desired domain as follows:

>> a = [1 4]; b = 5; w = [0 : 1 :1000];

>> freqs(b,a,w)

)(5)(4)(

4

5)( txty

dt

tdy

jjH

Page 49: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 49

Pole-Zero Plots and System Transfer Functions

• Say we have the system transfer function

• Read in the numerator and denominator as polynomials:

>> num = [1 3]

>> denom = [1 2 10]

• Get a pole-zero plot, with a title, by typing:

>> pzmap(num, denom), title („Pole-Zero Plot‟)

• Improve the scaling on the axes by setting it manually:

>> Axis([-4 4 -4 4])

• To find the values of the poles and zeros explicitly, type

>> poles = roots(denom), zeros = roots(num)

102

3)(

2

ss

ssH

Page 50: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 50

Partial Fraction Expansion

• Consider the system transfer function

• As before, read in polynomials a (for the denominator coefficients) and

b (for the numerator coefficients), both in descending order of powers.

• Use the function residue as shown below to obtain the residues in a

vector called res and the respective poles in a vector called pls:

>> a = [1 1.5 .5]; b = [1 2];

>> [res, pls] = residue(b,a)

5.5.1

2)(

2

ss

ssH

Page 51: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

User-Defined Functions : Function m-files

• Functions are just a special type of m-file or script.

• The first word must be: function

• The first line is of the form:

function [output_parameter_list] = function_name(input_parameter_list)

• After the first word (function), put the (optional) output parameters inside

square brackets [ ]. (Omit the square brackets and “=“ sign if there are no

output parameters.) The square brackets can also be omitted if there is

only one output parameter.

• The function_name is what we will use to call the function from the

command window. It must be the same as the file name (without the

“.m”).

• After the file name is the (optional) input_parameter_list.3/5/2011 Comprehensive MATLAB 51

Page 52: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

User-Defined Functions : Function m-files

• Good Practice: Don‟t alter any of the input parameters with the code in

your function. Input and Output parameters

• The input and output variables can be of any type: scalars, vectors,

matrices, or strings.

• Example: to create the function m-file titled: farh2cels

– Go to the file menu, and select New function.

3/5/2011 Comprehensive MATLAB 52

function [ output_args ] = Untitled2( input_args )

%UNTITLED2 Summary of this function goes here

% Detailed explanation goes here

end

MATLAB will

generate the

template

shown here.

Save as: fahr2cels

Page 53: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

User-Defined Functions : Function m-files

function temp_cels = fahr2cels(temp_fahr)

% farh2cels converts temperature from degrees F to degrees C.

% Thus function converts the input argument (temperature in degrees

% Fahrenheit) to temperature (in degrees Celsius.)

temp_cels = (5/9)*(temp_fahr - 32);

End

From the command window, to convert 100F to C, type:

>> fahr2cels(100)

ans =

37.7778

Converting a vector containing several temperatures in F :

>> X = [32 70 100]; Y = fahr2cels(X)

Y = 0 21.1111 37.7778

3/5/2011 Comprehensive MATLAB 53

Page 54: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 54

Simulink and Toolboxes

• Simulink: a computer environment for simulation of dynamic systems

• Toolboxes of particular interest for ECE students

– Symbolic Math

– Signal Processing

– Control System

– Communications

– Partial Differential Equations

• Blocksets of particular interest for ECE students

– DSP

– Communications

• To determine what products are on your computer, type:

> ver

Page 55: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 55

Building a Model in Simulink

- Sinewave Example -

Goal of this Example: Display a noisy sinewave as on oscilloscope

1. Before building the model, enter MATLAB and type

> commstartup

> simulink

(The first command sets the default simulation parameters that are best for

communications models. The second command opens a library browser

that will display the libraries for the products on your computer.)

2. To open a particular library, click on the + sign to the left of the blockset

name. The library contents will appear in the right-hand window pane.

• Important models for communication systems are in the libraries

of the Communications Blockset, the DSP Blockset, and

Simulink.

Page 56: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 56

Building a Model in Simulink

- Sinewave Example , cont.‟-

3. Open a model window by going to the File menu and selecting New

Model.

4. In the library browser, click on the + sign by the Signal Processing

blockset; then click Signal Processing Sources in the left plane and

find the Sine Wave block in the right pane.

3. Drag the Sine Wave block to the model window.

4. In the library browser (left pane), click on Signal Processing Sinks.;

then drag the Vector Scope block (from the right pane) into the

model window, and drop it (way) to the right of the Sine Wave.

5. Connect the blocks by first clicking on the Sine Wave block, then hit

the control key while clicking on the Vector Scope block.

Page 57: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 57

Building a Model in Simulink

- Sinewave Example , cont.‟-

• Double-click on the Sine Wave block to bring up its “mask” or dialog box;

• Change the parameters as follows:

– Amplitude: 5

– Frequency: 20 Hz ( T = 1/20 = .05 sec. = 50 ms)

– Samples/Frame: 100

• At the top of the model window, select the Simulation menu Configuration Parameters;

• Note that the Stop time should say inf, meaning that the simulation will run until we select Stop from the Simulation menu.

• Click the Data Inport/Export tab (left menu), and be sure that the boxes next to Time and Output under Save to workspace are not checked. (This saves memory.)

Page 58: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 58

Building a Model in Simulink

- Sinewave Example, with AWGN -

• To run the model, go to the Simulation menu and select Start. A scope display should appear, displaying a sinewave with amplitude 5 volts and period 50 ms.

• To stop the simulation, go to the Simulation menu and select Stop.

• Adding noise to the model: Return to the Library Browser and open the Communications blockset by clicking on its plus sign; click on the Channels library, and select the AWGN channel token.

• Drag the AWGN channel token to the model window, and drop it on the line connecting the sinewave to the scope. This will automatically connect the channel to the sinewave and the scope.

• Double click on the AWGN channel token to bring up its dialog box (or mask), and set the mode to Signal to noise ratio (SNR); then click O.K., and run the simulation. Remember you must explicitly tell it to stop.

Page 59: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

Some Useful GUI‟s

• For Controls and Linear Systems: >> ltiview

• For visualizing signals: >> sptool

• For Probability: >> disttool

• brings up a GUI to display pdf‟s and cdf‟s for a many types of random variables, with settable parameters

• For Filter Design: >> fdatool

3/5/2011 Comprehensive MATLAB 59

Page 60: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 60

GUI: LTIVIEW

• Say we want to analyze the system with transfer function:

H(s) =

• MATLAB Code:

>> num = [.3 1]; den = [.001 .01 1];

>> H = tf(num, den) % creates transfer function object

>> ltiview(H) % brings of GUI for viewing lti systems

• Right-click on the graph to see:

– Step response

– Impulse response

– Bode Plot

– Nyquist Plot

1s01.s001.

1s3.2

Page 61: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 61

GUI: LTIVIEWStep Response

Time (sec)

Am

plit

ude

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7-2

-1

0

1

2

3

4

5

6

7

• From edit menu: change user preferences (to change units, line

styles, etc.

• From file menu: “Print to Figure” to generate a figure for editing

plot features and exporting figure.

– Then: “Edit Figure Properties”, “Edit Axis Properties”, etc.

Page 62: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

D. van Alphen 62

GUI: Sptool (Signal Processing Tool)

• A built-in GUI that allows you to import & analyze signals (hear, see,

zoom, … ) and filters; type: >> sptool

• Built-in signals (left menu): bird chirp, train whistle, spoken word MATLAB

(other signals can be imported)

• Select a particular signal; select View to bring up the Browser; From top

menu, select the Speaker icon. Drag the red vertical marker lines to hear

more or less of the soundO-scope View: Bird Chirp

Page 63: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

D. van Alphen 63

Sptool – A Signal Processing Tool

(Part of Signal Processing Toolbox)

• The middle menu (Filters View) can be used to view the mag. response,

phase response, impulse response, step response, filter coefficients and the

pole-zero plot for filters

• Not useful for filter design (See FDATool)

• The right-most menu (Spectra View) can be used to view signals in the

frequency domain (calculated with the FFT).

0 0.5 1 1.5 2 2.5 3 3.5 4

-70

-60

-50

-40

-30

-20

-10

0

Frequency (kHz)

Mag

nitu

de (

dB)

Magnitude Response (dB)

FIR Filter:

Magnitude

Response,

|H(f)|

Page 64: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

ECE 699 64

An Easy FIR Filter in MATLAB

- Parks-McClellan Filters -

Parks-McClellan Filters

1. First hand-sketch the “piece-wise linear” desired magnitude response that

you are aiming for, using normalized frequencies

Example – BPF to pass the musical note: C2 = 64.21 Hz, where fs = 500

0 .2416 .2536 .2696 .2816 1

1

(not to scale)

64.21/(fs/2) = .2616

Page 65: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

ECE 699 65

Parks-McClellan Filters, continued

2a. Then make a vector (f) of the critical frequencies (from the normalized frequency axis of your sketch):

f = [0 .2416 .2536 .2696 .2816 1]

2b. Make a vector (a) of the corresponding amplitude levels of the desired frequency response, giving the amplitude for each frequency, from your sketch:

a = [0 0 1 1 0 0]

3. Finally, call for the vector of coefficients, b, (say of length 10) for the FIR:

b = firpm(9, f, a)

Always the same

for a BPF

Page 66: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

ECE 699 66

>> help firpm

Parks-McClellan optimal equiripple FIR filter design.

B = FIRPM(N, F, A) returns a length N+1 linear phase (real, symmetric

coefficients) FIR filter

F is a vector of frequency band edges in pairs, in ascending order between 0 and

1, where 1 corresponds to half the sampling frequency.

(1 fs/2 = 1/(2Ts))

A is a real vector the same size as F which specifies the desired amplitude of the

frequency response of the resultant filter B.

The desired response is the line connecting the points (F(k), A(k)) and (F(k+1),

A(k+1)) for odd k; FIRPM treats the bands between F(k+1) and F(k+2) for odd k

as "transition bands" or "don't care" regions. Thus the desired amplitude is

piecewise linear with transition bands. The maximum error is minimized.

Page 67: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 67

The Symbolic Toolbox

• MATLAB is designed to do vectorized numerical

calculations.

• Without the Symbolic Toolbox, it wouldn‟t be able to do

things like:

– Expand the product (x+4)5

– Find the anti-derivative of sinh(x)

– Simplify (sin2(x) + cos2(x))

• With the Symbolic Toolbox, we can do all of the above

closed-form calculations, and much more, using portions

of a program called Maple.

Page 68: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

Symbolic Toolbox – Some Examples

• First create symbolic variables:

>> syms x y a t

• New symbolic variables can be defined as functions of those already

defined:

>> r = sin(x)^2 + cos(x)^2

>> g = atan(y/x)

>> h = (x + y)^4

• Expressions can be simplified and/or expanded:

>> r = simple(r) % returns: r = 1

>> expand(h) % ans : x^4 + 4*x^3*y + …+ 4*x*y^3 + y^4

3/4/11 Comprehensive MATLAB 68

Page 69: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

Symbolic Toolbox – More Examples

• We can factor expressions:

>> syms z; factor(z^3 + z^2 - 8*z - 12)

ans =

(z - 3)*(z + 2)^2

• We can solve (non-linear equations), say e5x = 2y

>> syms x y

>> eq = 'exp(5*x) = 2*y'

eq =

exp(5*x) = 2*y

>> [x] = solve(eq,x)

x =

log(2*y)/5

3/5/2011 Comprehensive MATLAB 69

Page 70: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

Symbolic (Closed-form) Differentiation & Integration

Use diff(…) to find the derivative of the argument

>> diff(x^4) % performs d/dx; ans: 4 x^3

>> diff(x^3 + y*x, y) % performs d/dy, due to 2nd argument

>> diff(x^3, 2) % performs d2/dx2, due to 2nd argument

>> diff(x^3 + y*x) % ans: 3x^2 + y

Note: derivative was taken “dx” since no 2nd argument was given

Use int(…) to find the integral of the argument

>> int(x^4) % ans: x^5/5

>> int(a^x) >> int(a^x) % ans : a^x/log(a) (integrated dx)

Note: as with diff, 2nd argument can specify the variable of integration

3/5/2011 Comprehensive MATLAB 70

Page 71: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

Using Ezplot

• Ezplot is a user-friendly plotter (part of Symb. Toolbox)

• Syntax: >> ezplot(fun) or >> ezplot(fun,[min,max])

• Example: >> ezplot('x^2/4 + y^2/8 = 1')

3/5/2011 Comprehensive MATLAB 71

-6 -4 -2 0 2 4 6-6

-4

-2

0

2

4

6

x

y

x2/4 + y

2/8 = 1

Page 72: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

Using Ezplot, continued

>> f = 1/(5*sin(x) - 3)

f =

1/(5*sin(x) - 3)

>> ezplot(f)

3/5/2011 Comprehensive MATLAB 72

-6 -4 -2 0 2 4 6

-1.5

-1

-0.5

0

0.5

1

1.5

2

x

1/(5 sin(x) - 3)

Page 73: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

Using Ezplot3

• For a 3-D Parametric Plot:

• >> ezplot3('cos(t)', 'sin(t)', t, [-12 12])

3/5/2011 Comprehensive MATLAB 73

-1-0.5

00.5

1

-1-0.5

00.5

1-20

-10

0

10

20

x

x = cos(t), y = sin(t), z = t

y

z

Page 74: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 74

Using funtool for Closed-form Answers

• The command funtool is part of the Symbolic Toolbox

• From the command window, type

>> funtool

• This should bring up 3 windows, 2 of which are graphical and

1 of which looks like a calculator.

• Use the calculator to enter functions f(x) and g(x), and

constant a. (Just make up some polynomial or trig functions,

for example.)

• Then use the calculator window to multiply f and g, integrate

f with respect to x, differentiate g with respect to x, etc.

Page 75: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 75

More on funtool

• funtool : an interactive function calculator for functions of a

single variable, x

• Two functions, f(x) and g(x), and always displayed

• The answer usually replaces f(x).

• The controls labeled 'f = ' and 'g = ' can be edited to define

new functions, and the control labeled 'a = ' can be edited to

define a new constant..

• The control labeled 'x = ' may be changed to specify a new

domain.

Page 76: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 76

funtool Example

• f = tan(x)*(sin(x)^2 + cos(x)^2)

• g = sin(x)

• a = 1/2, x = (-2p, 2p)

• f*g , followed by simplify f: yields product tan(x) sin(x)

• Unfortunately, you can‟t copy the graphs (say to paste them into some

document.

-8 -6 -4 -2 0 2 4 6 8-70

-60

-50

-40

-30

-20

-10

0

10

20

30

Page 77: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 77

Fun & Games

• Type the following:

>> load handel % file w/part of Handel‟s Messiah

>> sound(y)

• Type the following

>> calendar % calendar for current month

>> calendar(2004,5) % calendar for May, 2004

• Type the following

>> magic(4) % makes a 4x4 magic square

• Type the following

>> spy % loads & displays Mad Mag. % image

Page 78: MATLAB - Advanced Workshop Overvieapr69082/Matlab/matlabadvanced.pdf– MATLAB will return with and HTML page (from the Help Browser) giving the syntax, an example, and a thorough

3/5/2011 Comprehensive MATLAB 78

Web Sites of Interest

• www.mathworks.com

• www.matlabcentral.com

• www.mathtools.net

• http://integrals.wolfram.com

• www.onlineconversion.com