Lab Manual - University of Arkansas

104
ELEG 3124 Signal and Systems Lab Manual Jingxian Wu Department of Electrical Engineering University of Arkansas This work is licensed under: Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)

Transcript of Lab Manual - University of Arkansas

Page 1: Lab Manual - University of Arkansas

ELEG 3124 Signal and Systems

Lab Manual

Jingxian Wu

Department of Electrical Engineering

University of Arkansas

This work is licensed under:

Attribution-NonCommercial-ShareAlike 4.0 International

(CC BY-NC-SA 4.0)

Page 2: Lab Manual - University of Arkansas

Department of Electrical EngineeringUniversity of Arkansas

A Tutorial on Matlab

Ch. 1 Introduction

Dr. Jingxian Wu

[email protected]

Page 3: Lab Manual - University of Arkansas

OUTLINE

2

β€’ Introduction: what is Matlab?

β€’ Basics

β€’ Simple Arithmetic

β€’ Matlab workspace

β€’ Getting help

β€’ Exercises

Page 4: Lab Manual - University of Arkansas

INTRODUCTION

β€’ What is Matlab

– Matrix Labortary

– A high level programming language for scientific and engineering

computing

– Developed by Mathworks Inc.

β€’ What can Matlab do?

– Scientific computations (a very powerful calculator)

– Plotting data and functions

– Implementation of algortihms

– Simulating different systems

– Interfacing with programs written in other languages (C, C++, Java,

Fortran)

Page 5: Lab Manual - University of Arkansas

INTRODUCTION

β€’ Application areas

– Engineering

– Science

– Biomedical

– Economics

– ……

Page 6: Lab Manual - University of Arkansas

OUTLINE

5

β€’ Introduction: what is Matlab?

β€’ Basics

β€’ Simple arithmetic

β€’ Matlab workspace

β€’ Getting help

β€’ Exercises

Page 7: Lab Manual - University of Arkansas

BASICS

Enter Matlab command here

Matlab command window

Page 8: Lab Manual - University of Arkansas

BASICS

β€’ Matlab command prompt: >>– You can type Matlab commands after the prompter

β€’ Example: Matlab as a calculator>> 3+2*5

ans =

13

>> sqrt(1+6*8)-3^2

ans =

-2

>> 48/(6+2)

ans =

6

>> Basic operators

Page 9: Lab Manual - University of Arkansas

BASICS

β€’ Variables– We can assign values to variables

– Examples

>> x = 3

x =

3

>> y = 5

y =

5

>> x+y*2

ans =

13

>>

Page 10: Lab Manual - University of Arkansas

BASICS

β€’ Semicolon

– Add semicolon at the end of an expression can suppress displaying the

output

– Example:

>> x = 3;

>> y = 2;

>> z = (x^2-1)/y;

>> z

z =

4

>>

Page 11: Lab Manual - University of Arkansas

BSAICS

β€’ The β€œans” variable

– If we do not assign the result of an expression to a variable, it will be stored in the β€œans” variable by default.

– Example:

>> (12/(4+2)+5)*2

ans =

14

>> ans*2

ans =

28

>>

Page 12: Lab Manual - University of Arkansas

OUTLINE

11

β€’ Introduction: what is Matlab?

β€’ Basics

β€’ Simple arithmetic

β€’ Matlab workspace

β€’ Getting help

β€’ Exercises

Page 13: Lab Manual - University of Arkansas

SIMPLE ARITHMETIC

β€’ Matlab supports a long list of basic mathematical functions

– Elementary Matlab functions:

– You can use β€œhelp command” to get more detailed information about each

function

Elementary Matlab functions

Page 14: Lab Manual - University of Arkansas

SIMPLE ARITHMETIC

β€’ Constants– Predefined constants

– Avoid using i or j as your variables

– Example:

>> clear all

>> (3*i)^2

ans =

-9

>> i = 2;

>> (3*i)^2

ans =

36

>>

Avoid doing this because i is a reserved constant!

Common constants

Page 15: Lab Manual - University of Arkansas

SIMPLE ARITHMETIC

β€’ Example:

– Use Matlab to evaluate the expression:

– y= exp βˆ’π‘Ž + cos 𝑏 log 𝑐

– where π‘Ž = βˆ’2 + 3𝑖, 𝑏 =3πœ‹

5, 𝑐 = 10

Page 16: Lab Manual - University of Arkansas

OUTLINE

15

β€’ Introduction: what is Matlab?

β€’ Basics

β€’ Simple Arithmetic

β€’ Matlab workspace

β€’ Getting help

β€’ Exercises

Page 17: Lab Manual - University of Arkansas

MATLAB WORKSPACE

β€’ Matlab workspace

– The collection of variables that have been defined.

– We can use the who command to display all available variables.

– Example:

>> x = 3;

>> y = 5;

>> z = x^2 + y;

>> sqrt(16)/2;

>> who

Your variables are:

ans x y z

>>

Workspace

Page 18: Lab Manual - University of Arkansas

MATLAB WORKSPACE

β€’ Matlab workspace– Use the clear command to clear the part or the entirety of the workspace

– Example:

>> x = 3;

>> y = 5;

>> z = x^2 + y;

>> who

Your variables are:

x y z

>> clear x

>> who

Your variables are:

ans y z

>> clear

>> who

>> y+1

Undefined function or variable β€˜y'.

Error message

Page 19: Lab Manual - University of Arkansas

MATLAB WORKSPACE

β€’ Command history

– At the command prompt, you can use the β€œup arrow” key and β€œdown

arrow” key on your keyboard to recall to previously typed command.

– Once a previous command is recalled, you can use the β€œleft arrow” and

β€œright arrow” keys to edit the command.

– Demo:

Page 20: Lab Manual - University of Arkansas

MATLAB WORKSPACE

β€’ Command assistance

– After typing a few letters (e.g. xyz), you can use the β€œtab” key on your

keyboard to prompt you with all available commands and variables that

start with β€œxyz”

– Example:

I typed β€œx” at the command prompt, then hit the β€œtab” key. Matlab pops

a small window displaying all variables and commands starting with β€œx”

Command assistance

Page 21: Lab Manual - University of Arkansas

OUTLINE

20

β€’ Introduction: what is Matlab?

β€’ Basics

β€’ Simple Arithmetic

β€’ Matlab workspace

β€’ Getting help

β€’ Exercises

Page 22: Lab Manual - University of Arkansas

GETTING HELP

β€’ To get more information about a Matlab command

– Use help command_name

– The help command is your best friend!

– When not sure about a command, always use help!

– Example

>> help sqrt

sqrt Square root.

sqrt(X) is the square root of the elements of X. Complex

results are produced if X is not positive.

See also sqrtm, realsqrt, hypot.

Overloaded methods:

codistributed/sqrt

gpuArray/sqrt

Reference page in Help browser

doc sqrt

Page 23: Lab Manual - University of Arkansas

GETTING HELP

β€’ Find a command for a certain operation

– Use the lookfor keyword command

– The command returns a list of Matlab functions that has keyword in the first section of the help file.

– Example:

β€’ I want to find a command that can play audio files. The lookfor command

>> lookfor audio

audioplayer - Audio player object.

audiorecorder - Audio recorder object.

audiodevinfo - Audio device information.

audioinfo - Information about an audio file.

audioplayerreg -

audioread - Read audio files

audiorecorderreg - AUDIOPLAYERREG

audiouniquename - Assign unique variable name in workspace.

audiowrite - write audio files

avgate

…

Page 24: Lab Manual - University of Arkansas

OUTLINE

23

β€’ Introduction: what is Matlab?

β€’ Basics

β€’ Matlab workspace

β€’ Getting help

β€’ Exercises

Page 25: Lab Manual - University of Arkansas

EXERCISES

– 1. Use Matlab to calculate the following expressions

β€’ (1) π‘₯ =1

21+

122βˆ’2

36+log(5)

β€’ (2) 𝑦 = 2

β€’ (3) 𝑧 =π‘₯

𝑦+ log π‘₯ log10(𝑦) + π‘₯𝑦

β€’ (4) π‘₯

0

β€’ (5) π‘₯ = βˆ’9

– 2. In the Matlab command window, use the β€œupper arrow” key on your

keyboard to recall the command corresponding to the command for Ex.

1(1). Then use the β€œleft arrow” and β€œright arrow” key to edit the command

such that you can calculate

π‘₯ =1

22+

122βˆ’2

36+log(7)

Page 26: Lab Manual - University of Arkansas

EXERCISES

– 3. Calculate x + z. Then use the clear command to clear the variables x

and z, and try x + z again.

– 4. Use the lookfor command to find out the command corresponding to

the log2(π‘₯)function, then use the help command to obtain detailed

information about the function.

Page 27: Lab Manual - University of Arkansas

Department of Electrical EngineeringUniversity of Arkansas

A Tutorial on Matlab

Ch. 2 Matrix Operations

Dr. Jingxian Wu

[email protected]

Page 28: Lab Manual - University of Arkansas

OUTLINE

2

β€’ Vectors

β€’ Matrices

β€’ Matrix operations

β€’ Exercises

Page 29: Lab Manual - University of Arkansas

VECTORS AND MATRICES

β€’ Vectors and matrices are fundamental to Matlab

– Matlab is designed specifically for vector and matrix operations.

– Direct vector and matrix operations are usually much faster compared to

process scalars with loops

– Try to use vector and matrix as often as possible

β€’ minimize the use of loops (loops are slow in Matlab)

Page 30: Lab Manual - University of Arkansas

VECTORS

β€’ Vector

– Define a row vector (use , as the separator)

>> a = [3, 1, 2, 8] % [ ] indicates a vector

a =

3 1 2 8

– Define a column vector (use ; as the separator)

>> b = [3;1;2;8]

b =

3

1

2

8

– Transpose operator .’ (a dot followed by an apostrophe)

>> b.'

ans =

3 1 2 8

Page 31: Lab Manual - University of Arkansas

VECTORS

β€’ More ways of definition vectors

– Starting from 1, ends at 10, with a step size 2

>> c = [1:2:10] % the bracket is optional

c =

1 3 5 7 9

– Starting from 5, ends at 8, with a step size 1

>> d = 5:8

d =

5 6 7 8

Page 32: Lab Manual - University of Arkansas

VECTORS

β€’ More ways of defining vectors (Cont’d)

– Starting from 6, ends at 0, with a step size -2

>> e = [6:-2:0]

e =

6 4 2 0

– Generate 5 equally spaced points between 2 and 20

>> linspace(2, 20, 5)

ans =

2.0000 6.5000 11.0000 15.5000 20.0000

Page 33: Lab Manual - University of Arkansas

VECTORS

β€’ Vector indexing

Assume a = [3 1 2 8]

– The 3rd element of a vector

>> a(3)

ans =

2

– The 2, 3, 4th elements (vectors can be used as indices)

>> a(2:4) % similarly a(2:end) since a only has 4 elements

ans =

1 2 8

Page 34: Lab Manual - University of Arkansas

VECTORS

β€’ Vector indexing

Assume a = [3 1 2 8]

– The 2nd and 4th elements

>> a(2:2:4)

ans =

1 8

– The 1st and 4th elements (be careful about the bracket, which is used to

indicate a vector)

>> a([1,4])

ans =

3 8

Page 35: Lab Manual - University of Arkansas

OUTLINE

9

β€’ Vectors

β€’ Matrices

β€’ Matrix operations

β€’ Exercises

Page 36: Lab Manual - University of Arkansas

MATRICES

β€’ Define a matrix

– Define a 2 x 3 matrix

>> a = [2, 5, 7; 1, 4, 9]

a =

2 5 7

1 4 9

– Matrix transpose .’

>> a.'

ans =

2 1

5 4

7 9

Page 37: Lab Manual - University of Arkansas

MATRICES

β€’ Matrix indexing

a =2 5 71 4 9

– access the (1, 3)-th element (1st row, 3rd column)

>> a(1, 3)

ans =

7

– access the first row

>> a(1, :)

ans =

2 5 7

– access the 2nd column

>> a(:, 2)

ans =

5

4

Page 38: Lab Manual - University of Arkansas

MATRICES

β€’ Matrix indexing

a =2 5 71 4 9

– Access the 2nd and 3rd element on the 2nd row

>> a(2, [2,3])

ans =

4 9

– Access the 1st and 3rd columns

>> a(:, [1, 3])

ans =

2 7

1 9

– In general

a(row_index, column_index)

Page 39: Lab Manual - University of Arkansas

MATRICES

β€’ Matrix indexing

b =1 2 34 5 67 8 9

– Create a submatrix that contains the 2nd and 3rd rows, and 1st and 3rd

columns

>> b([2, 3], [1, 3])

ans =

4 6

7 9

– Exchange the 1st and 3rd column

>> b(:, [3, 2, 1])

ans =

3 2 1

6 5 4

9 8 7

Page 40: Lab Manual - University of Arkansas

MATRIX

β€’ Build a matrix with vectors

– Build a matrix with row vectors

>> v1 = [1 3 5];

>> v2 = [2 4 6];

>> m = [v1; v2] % semicolon separates rows

m =

1 3 5

2 4 6

– Build a matrix with column vectors

>> c1 = [1; 2]; % semicolon separates rows (a column vector with 2 rows)

>> c2 = [3; 4];

>> c3 = [5; 6];

>> m2 = [c1, c2, c3] % comma separates columns ( a matrix with 3 columns)

m2 =

1 3 5

2 4 6

Page 41: Lab Manual - University of Arkansas

OUTLINE

15

β€’ Vectors

β€’ Matrices

β€’ Matrix operations

β€’ Exercises

Page 42: Lab Manual - University of Arkansas

MATRIX OPERATIONS

β€’ Arithmetic

m1 =2 5 71 4 9

, m2 =1 2 34 5 6

, 𝑣1 = 7 8 9 , 𝑣2 =123

,

– Summation and subtraction (matrix of vector size must match)

>> m1-m2

ans =

1 3 4

-3 -1 3

>> v1+v2

Error using +

Matrix dimensions must agree.

>> v1+v2.'

ans =

8 10 12

Page 43: Lab Manual - University of Arkansas

MATRIX OPERATIONS

β€’ Arithmetic

m1 =2 5 71 4 9

, m2 =1 2 34 5 6

, 𝑣1 = 7 8 9 , 𝑣2 =123

,

– Element wise multiplication: .* (dot followed by star)

>> m1.*m2

ans =

2 10 21

4 20 54

– Element wise division: ./ (dot followed by slash)

>> v1./v2

Error using ./

Matrix dimensions must agree.

>> v1./v2.'

ans =

7 4 3

Page 44: Lab Manual - University of Arkansas

MATRIX OPERATION

β€’ Arithmetic

m1 =2 5 71 4 9

, m2 =1 2 34 5 6

, m3 =1 2 33 1 22 3 1

– Matrix multiplication (the inner dimension of the matrices must match)

>> m1*m2 % m1 has 3 columns, m2 has 2 rows, inner dimension mismatch

Error using *

Inner matrix dimensions must agree.

>> m1*m3 % m1 has 3 columns, m3 has 3 rows

ans =

31 30 23

31 33 20

– Inverse of a square matrix

>> inv(m3)

ans =

-0.2778 0.3889 0.0556

0.0556 -0.2778 0.3889

0.3889 0.0556 -0.2778

Page 45: Lab Manual - University of Arkansas

MATRIX OPERATIONS

β€’ Arithmetic

m1 =2 5 71 4 9

, m2 =1 2 34 5 6

, 𝑣1 = 7 8 9 ,

– Add v2 to the 2nd row of m1, and assign the result to a new matrix mat1

>> mat1 = m1;

>> mat1(2, :) = mat1(2, :) + v1

mat1 =

2 5 7

8 12 18

– Replace the 3rd column of m2 with the 1st column of m1, and assign the

result to a new matrix mat2

>> mat2 = m2;

>> mat2(:, 3) = m1(:, 1)

mat2 =

1 2 2

4 5 1

Page 46: Lab Manual - University of Arkansas

MATRIX OPERATION

β€’ Operation between a matrix and a scalar

m1 =2 5 71 4 9

– Elementwise operations with the scalar

>> m1+2

ans =

4 7 9

3 6 11

>> m1*2

ans =

4 10 14

2 8 18

>> m1/2

ans =

1.0000 2.5000 3.5000

0.5000 2.0000 4.5000

Page 47: Lab Manual - University of Arkansas

MATRIX OPERATION

β€’ Transpose (.’) v.s. complex transpose (’)

m4 =2 + 𝑖 5 + 2𝑖 7 + 3𝑖1 4 9

– Transpose operator: .’

>> m4.'

ans =

2.0000 + 1.0000i 1.0000

5.0000 + 2.0000i 4.0000

7.0000 + 3.0000i 9.0000

– Complex transpose operator: ’ (transpose and complex conjugate)

>> m4'

ans =

2.0000 - 1.0000i 1.0000

5.0000 - 2.0000i 4.0000

7.0000 - 3.0000i 9.0000

Page 48: Lab Manual - University of Arkansas

MATRIX OPERATIONS

β€’ Logic operators

m1 =2 5 71 4 9

,m5 =2 2 34 5 9

– Example: extract all elements in m1 that is > 4

>> logic_mat = (m1 > 4)

logic_mat =

0 1 1

0 0 1

>> m1(logic_mat)

ans =

5

7

9

% or equivalently

>> m1(m1>4)

ans =

5

7

9

Page 49: Lab Manual - University of Arkansas

MATRIX OPERATIONS

β€’ Dimension of a matrix

m1 =2 5 71 4 9

– size( ): returns the dimension of a matrix

>> size(m1)

ans =

2 3

>> [m,n] = size(m1)

m =

2

n =

3

Page 50: Lab Manual - University of Arkansas

MATRIX OPERATIONS

β€’ Diagonal of a matrix

m3 =1 2 33 1 22 3 1

, 𝑣1 = 7 8 9 ,

– diag(a): returns the main diagonal of the matrix a

>> diag(m3)

ans =

1

1

1

– diag(v1): creates a diagonal matrix with vector v1 on its diagonal

– >> diag(v1)

ans =

7 0 0

0 8 0

0 0 9

Page 51: Lab Manual - University of Arkansas

MATRIX OPERATIONS

β€’ Generate special matrices

– All-one matrix

>> ones(2, 3)

ans =

1 1 1

1 1 1

– All-zero matrix

>> zeros(1, 2)

ans =

0 0

– Identity matrix

>> eye(3)

ans =

1 0 0

0 1 0

0 0 1

Page 52: Lab Manual - University of Arkansas

OUTLINE

26

β€’ Vectors

β€’ Matrices

β€’ Matrix operations

β€’ Exercises

Page 53: Lab Manual - University of Arkansas

EXERCISES

– 1. Create a row vector that starts with -10, ends at 18, with a step size of 4

– 2. Create a column vector that starts with 6, ends at -9, with a step size -3

– 3. Create a row vector that starts with 1, ends at 90, and has exactly 20

elements

– 4. Create the following three matrices

A =2 3 71 5 6

, B =1 2 34 5 6

, C =1 + 𝑖 23 4 + 𝑖5 6

,

– 5. Calculate A + B, B + 2, A - transpose(C), element-wise A.*B and A./B

– 6. Is A*B valid? Is A*transpose(B) valid?

Page 54: Lab Manual - University of Arkansas

EXERCISES

– 7. Use matrix indexing access the following elements:

β€’ The element on the 2nd row and 3rd column of A

β€’ The 2nd row of B

β€’ The 3rd column of A

β€’ The elements on the 2nd row and 2nd and 3rd columns of A

β€’ A new 2x2 matrix D, the 1st column of D is the 2nd column of A, and

the 2nd column of D is the 3rd column of B

– 8. Use a logic matrix to indicate the locations where the elements of A and

B are the same.

– 9. Find the elements of B that is less than or equal to 3

Page 55: Lab Manual - University of Arkansas

Department of Electrical EngineeringUniversity of Arkansas

A Tutorial on Matlab

Ch. 3 Programming in Matlab

Dr. Jingxian Wu

[email protected]

Page 56: Lab Manual - University of Arkansas

OUTLINE

2

β€’ Plotting

β€’ M-file Scripts

β€’ Functions

β€’ Control Flows

β€’ Exercises

Page 57: Lab Manual - University of Arkansas

PLOTTING

β€’ Simple plotting

>> x = [1 2 3 4 5];

>> y = [3 -1 2 -3 -4]; % vector x and y must be of the same length

>> plot(x, y)

>> x = linspace(0, 2*pi, 100);

>> y = cos(x + pi/3);

>> plot(x, y)

>> xlabel('x'); % add a label to the x-axis

>> ylabel('y'); % add a label to the y-axis

>> title('cos(x + \pi/3)'); % add a title to the figure

>> grid on; % turn on the grid

>> print –djpeg fig.jpg; % save the figure to a file.

Plot of Matlab

Page 58: Lab Manual - University of Arkansas

PLOTTING

β€’ Multiple curves in one figure

– Use the β€œhold on” command

>> x = [0:0.01:5];

>> y1 = cos(x);

>> y2 = exp(-x);

>> y3 = sinc(x);

>> plot(x, y1);

>> hold on;

>> plot(x, y2, 'k--'); % black, dashed line

>> plot(x, y3, 'r-.'); % red, dash-dot line

>> legend('cos(x)', 'exp(-x)', 'sinc(x)'); % adding legends

>> set(gca, 'fontsize', 14); % change the fontsize

Use β€œhelp plot” to find out more line styles and colors

Plot of Matlab

Page 59: Lab Manual - University of Arkansas

PLOTTING

β€’ Rescale a figure

– Use the axis command

>> x = [-20:0.01:20];

>> plot(x, sinc(x))

>> axis([-5, 5 -0.3 1]); % x range: [-0.5, 0.5], y-range: [-0.3, 1]

β€’ Close one or more figures

– figure(1); % make figure 1 the current figure

– close; % close the current figure

– close all; % close all figures

Page 60: Lab Manual - University of Arkansas

OUTLINE

6

β€’ Plotting

β€’ M-file Scripts

β€’ Functions

β€’ Control Flows

β€’ Exercises

Page 61: Lab Manual - University of Arkansas

M-FILE SCRIPTS

β€’ Script file:

– We can write a sequence of Matlab commands in an external file with

extension *.m

β€’ The file is usually called an m-file

– Execute the m-file file will execute all commands in the file

Page 62: Lab Manual - University of Arkansas

M-FILE SCRIPTS

β€’ Create a script file

– 1. In Matlab, click on File β†’ New β†’ Script, to load the default editor

– 2. In the editor, type the commands:

x = [0:0.01:10];

y1 = cos(x);

y2 = exp(-x);

plot(x, y1);

hold on;

plot(x, y1+y2, 'r--');

β€’ 3. Save the file. In the editor window, click on File β†’ Save β†’ test.m

β€’ 4. Execute the file. In the editor window, click on Debug β†’ Run test.m

Page 63: Lab Manual - University of Arkansas

M-FILE SCRIPTS

β€’ Execute the file

– Switch to the command window

– At the command prompt, type

>> test % note that .m is not included in the command

– Important: the m-file to be executed must be in the current working

directory

>> pwd % display the current working directory

ans =

c:\skydrive\teaching\ELEG3124\Matlab

>> ls *.m % list all m-files in the current working directory

test.m

Page 64: Lab Manual - University of Arkansas

OUTLINE

10

β€’ Plotting

β€’ M-file Scripts

β€’ Functions

β€’ Control Flows

β€’ Exercises

Page 65: Lab Manual - University of Arkansas

FUNCTIONS

β€’ Function

– A function can be defined and saved in a separate m-file

– Example

function y = average(x)

% function y = average(x)

% compute the average of a vector x, and return the value to y

N_element = length(x);

y = sum(x)/N_element;

– Must start with the keyword: function

– Save to an m-file: in the editor window, File β†’ Save β†’ average.m.

β€’ The name of the m-file must be the function name.

– The comments after the function title will be displayed when you type

β€œhelp average” in the command line

Page 66: Lab Manual - University of Arkansas

FUNCTIONS

β€’ Call the function

– In the command window

>> x = 1:10;

>> y = average(x)

>> z = sqrt(x);

>> average(z)

Page 67: Lab Manual - University of Arkansas

FUNCTION

β€’ Function with multiple inputs and/or outputs

function [addition, difference] = total_diff(x,

y)

% function [total, difference] = total_diff(x, y)

% find the sum and difference between two vectors

addition = x + y;

difference = x - y;

Page 68: Lab Manual - University of Arkansas

OUTLINE

14

β€’ Plotting

β€’ M-file Scripts

β€’ Functions

β€’ Control Flows

β€’ Exercises

Page 69: Lab Manual - University of Arkansas

CONTROL FLOWS

β€’ Matlab control flows:

– 1. if … elseif … else … end

– 2. for … end

– 3. while … end

Page 70: Lab Manual - University of Arkansas

CONTROL FLOWS

β€’ if … end

x = 10;

y = sqrt(x)-x/3;

if y < 0

'y is less than 0'

y = y + 1;

end

Page 71: Lab Manual - University of Arkansas

CONTROL FLOWS

β€’ if … else … end

x = 10;

y = sqrt(x)-x/3+1;

if y < 0

'y is less than 0'

y = y + 1;

else

'y is greater than or equal to 0'

y = y - 1;

end

Page 72: Lab Manual - University of Arkansas

CONTROL FLOWS

β€’ if … elseif … else … end

y = 0;

if y < 0

'y is less than 0'

y = y + 1;

elseif y == 0

'y is 0'

else

'y is greater than 0'

y = y - 1;

end

Page 73: Lab Manual - University of Arkansas

CONTROL FLOWS

β€’ for … end

for mm = 1:2:10

y(mm) = mm^2;

end

% or equivalently:

% this is more efficient

y = [1:2:10].^2;

Page 74: Lab Manual - University of Arkansas

CONTROL FLOWS

β€’ Double loops

A = [1 3 2; 4 -1 0];

[n_row, n_col] = size(A);

for mm = 1:n_row

row_avg(mm) = mean(A(mm, :));

for nn = 1:n_col

B(mm, nn) = A(mm, nn).^2;

end

end

% Alternatively and more efficiently

row_avg = mean(A, 2); % calculate the row average

B = A.^2;

Page 75: Lab Manual - University of Arkansas

CONTROL FLOWS

β€’ while … end

x = 1;

while x <= 20

x = 3*x+2;

end

Page 76: Lab Manual - University of Arkansas

OUTLINE

22

β€’ Plotting

β€’ M-file Scripts

β€’ Functions

β€’ Control Flows

β€’ Exercises

Page 77: Lab Manual - University of Arkansas

EXERCISES

– 1. Plot the real part, imaginary part, and amplitude of the following

function in the same figure. Use xlabel, ylable, legend, grid, and different

color and line styles for different curves. Use a font size of 14

𝑠 𝑑 = π‘’βˆ’π‘‘π‘’π‘—2πœ‹π‘‘, 0 ≀ 𝑑 ≀ 10

– 2. rescale the above curve for x between 0 and 5, and y between -2 and 2

– 3. Write a function to calculate the standard deviation of a vector, where

is the i-th element of the vector, is the average of the vector

β€’ Use the above function, evaluate the standard deviation of the

following vector

x = [0, 3, 1, 5, -2, -4, 3, 2, -5]

=

βˆ’=n

i

i xxn

y1

2)(1

ixx

Page 78: Lab Manual - University of Arkansas

EXERCISES

– 4. Write a Matlab function to generate the first n Fibonacci number, where

n is the function input. The Fibonacci number is defined as

β€’ Generate the first 10 Fibonacci number

– 5. Write a function, which takes a vector x as input. The output y is a

vector of the same size, defined as follows

β€’ Test your function with x = -3:3

– 6. Consider a sequnce

Use while loop to find out what is the smallest n such that

21

2

1

1

1

βˆ’βˆ’ +=

=

=

nnn FFF

F

F

βˆ’

==

=

0,

0,0

0,

2

nn

n

nn

n

xx

x

xx

y

12,0 2/3

11 +== βˆ’nn xxx

100nx

Page 79: Lab Manual - University of Arkansas

Department of Electrical EngineeringUniversity of Arkansas

A Tutorial on Matlab

Ch. 4 Symbolic Operations

Dr. Jingxian Wu

[email protected]

Page 80: Lab Manual - University of Arkansas

SYMBOLIC OPERATIONS

β€’ Symbolic operation:

– Analytically solving and manipulating symbolic mathematical expressions

β€’ All discussions in previous chapters are based on numerical solutions:

variables must have values

– In symbolic operations, the variables do not need to have a value

– For example, we can use symbolic operation to perform integration or

differentiation

Page 81: Lab Manual - University of Arkansas

SYMBOLIC OPERATIONS

β€’ Declare symbol variables

– Declare the variables a, b, x as symbolic variables (they do not have

numerical values),

– Define a symbolic function

>> syms a b x % declare symbolic symbols

>> f = x^a*exp(-b*x) % use symbolic symbols to define a symbolic function

f =

x^a/exp(b*x)

bxaexxf βˆ’=)(

Page 82: Lab Manual - University of Arkansas

SYMBOLIC OPERATIONS

β€’ Differentiation

– Find the first derivative of

β€’ With f(x) defined in the previous slide

>> diff_f = diff(f, x) % differentiation

diff_f =

(a*x^(a - 1))/exp(b*x) - (b*x^a)/exp(b*x)

>> simplify(diff_f) % ask Matlab to simplify the results

ans =

(x^(a - 1)*(a - b*x))/exp(b*x)

bxaexxf βˆ’=)(

Page 83: Lab Manual - University of Arkansas

SYMBOLIC OPERATIONS

β€’ Integration

– Find the indefinite integral of

>> syms a x

>> f2 = x*exp(-a*x)

f2 =

x/exp(a*x)

>> int_f = int(f2, x) % indefinite integral

int_f =

-(a*x + 1)/(a^2*exp(a*x))

axxexf βˆ’=)(2

Page 84: Lab Manual - University of Arkansas

SYMBOLIC OPERATIONS

β€’ Integral (cont’d)

– Calculate

>> int(f2, x, 0, 10)

ans =

1/a^2 - (10*a + 1)/(a^2*exp(10*a))

βˆ’

10

0

dxxe ax

Page 85: Lab Manual - University of Arkansas

SYMBOLIC OPERATIONS

β€’ Substitution

– The β€œsubs” command substitute a number of a symbol into a symbolic expression

– Example: evaluate the value of when a = 2, b = 1, and x = 3

>> syms a b x

>> f = x^a*exp(-b*x)

f =

x^a/exp(b*x)

>> subs(f, a, b, x, 2, 1, 3)

ans =

0.4481

>>

bxaexxf βˆ’=)(

Page 86: Lab Manual - University of Arkansas

SYMBOLIC OPERATIONS

β€’ Substitution

– Example:

β€’ Evaluate the integral of when a = 2

>> syms a x

>> f2 = x*exp(-a*x)

f2 =

x/exp(a*x)

>> int_f2 = int(f2, 0, 10)

int_f2 =

1/a^2 - (10*a + 1)/(a^2*exp(10*a))

>> subs(int_f2, a, 2)

ans =

0.2500

>>

βˆ’

10

0dxxe ax

Page 87: Lab Manual - University of Arkansas

SYMBOLIC OPERATIONS

β€’ Graphing functions with ezplot

– Example: plot when a = 2 and b = 1 for x in the range of [0, 10]

>> syms x y a b

>> f = x^a*exp(-b*x);

>> f3 = subs(f, a, b, 2, 1)

f3 =

x^2/exp(x)

>> ezplot(f3, [0, 10])

bxaexxf βˆ’=)(

Plot of Matlab

Page 88: Lab Manual - University of Arkansas

Lab 4 Introduction to Matlab

I. Lab Assignments

Part A: Review of Numerical Computations

1. Use a single Matlab command to create a vector consisting of all the EVEN

numbers between 7 and 101. Use a Matlab command to find out the number

of elements in the vector.

2. Create the following matrices:

168

734

152

A ,

027

832

613

B

a) Use a single Matlab command, find the sums of all the elements on the

same row of A.

b) Use a single Matlab command, find the summation of the elements on the

2nd

row of A.

c) Use a single Matlab command, find the product of the elements on the 1st

column of B.

d) Use a for loop, find the summation of the diagonal elements of A.

e) Find A.*B and A*B manually, and verify your results with Matlab.

3. Use Matlab to create a vector ,2tex ,10:1.0:0t

a) Add 5 to each element of x, and store the result in a vector.

b) Add 3 to only the ODD-index elements of x (e.g x(1), x(3), x(5)…), and

store the result in a new vector y.

4. Load the matrix A stored in random_matrix.mat (can be downloaded from

course website).

a) Find the dimension (size) of the matrix.

b) Find the number of elements in A that is greater than 0.

c) Find the number of elements in the 2nd

row of A that is greater than 0.

b) Find the summation of all the elements in A.

d) Find the summation of all the even-index element in the 3rd

row of A.

5. Write a Matlab function y = rms(x) and save it in rms.m in your work folder.

The input of the function is a vector x, the output of the function is a scalar y,

which is the root mean square value of the elements in x. That is

N

n

nxN

y1

2 )(1

Test your function with the input x = [1 5 2 3 8].

Page 89: Lab Manual - University of Arkansas

Part B: Review of Symbolic Computations

6. Go through pages 43 – 47 of the L. Chaparro book ( part of the Section 0.5.2

Soft Introduction to Matlab: Symbolic Computations). Practice all the

examples given in the textbook.

7. Plot the following functions for x between 0 and 5

a) )3exp( 2x

b) )2cos()exp( xx

c) sinc(x)

d) sinc )(2 x

8. Consider the function )3exp( 2xx

a) Find the differentiation

b) Find dxxx )3exp( 2

c) Find 3

0

2 )3exp( dxxx

II. Homework Assignments

Part A: Review of Numerical Computations (please finish all the following

problems with numerical computation)

1. Plot the following functions for -2 < t < 2, and save the results as jpeg files.

a) )2cos( ty

b) )3/2cos( ty

c)

0,

0,5

2

te

tey

t

t

d) )2cos(|| tey t

Part B: Symbolic Computations (please finish the following problem with

symbolic computation)

1. Consider the exponential function )exp( axy .

(a) Find dxdy / manually. Use Matlab to verify your calculation.

(b) Find b

adxax)exp( manually. Use Matlab to verify your calculation.

(c) Plot y when a = 2;

(d) Plot y when a = 0.5.

Page 90: Lab Manual - University of Arkansas

Lab 5 Continuous-Time Signals

I. Lab Assignments

Part A: Ramp/Unit Step Functions

1. Write a function, y = ustep(t), for the unit step function.

2. Write a function, y = uramp(t), for the unit ramp function.

3. Plot the following continuous time signals over βˆ’10 ≀ 𝑑 ≀ 10:

β€’ 𝑒(𝑑)

β€’ π‘Ÿ(𝑑)

β€’ 5𝑒(𝑑 βˆ’ 2)

β€’ 3π‘Ÿ(𝑑 + 5)

β€’ 𝑦(𝑑) = 3π‘Ÿ(𝑑 + 3) βˆ’ 6π‘Ÿ(𝑑 + 1) + 3π‘Ÿ(𝑑) βˆ’ 3𝑒(𝑑 βˆ’ 3)

β€’ 𝑦(𝑑) = 2π‘Ÿ(𝑑 + 2.5) βˆ’ 5π‘Ÿ(𝑑) + 3π‘Ÿ(𝑑 βˆ’ 2) + 𝑒(𝑑 βˆ’ 4)

β€’ 𝑦(𝑑) = sin(𝑑) βˆ— [𝑒(𝑑 + 3) βˆ’ 𝑒(𝑑 βˆ’ 3)]

Part B: Even/Odd signals

4. Create a function which returns the even and odd parts of a signal as follows.

5. Use the above function to find the even and odd parts of the following

continuous signal and plot the main signal beside its odd and even parts

inside one figure with different colors: (assume βˆ’10 ≀ 𝑑 ≀ 10)

β€’ 𝑦(𝑑) = 2π‘Ÿ(𝑑 + 2.5) βˆ’ 5π‘Ÿ(𝑑) + 3π‘Ÿ(𝑑 βˆ’ 2) + 𝑒(𝑑 βˆ’ 4)

Part C: Sum of Periodic Signals

6. Plot the following signal over βˆ’10 ≀ 𝑑 ≀ 10 . Is the sum signal still periodic?

If so, what is the period?

β€’ π‘₯1 (𝑑) = 1 + 1.5 π‘π‘œπ‘ (2 Ξ©0𝑑) βˆ’ 0.6 π‘π‘œπ‘ (4Ξ©0𝑑) Ξ©0 = πœ‹/10

Page 91: Lab Manual - University of Arkansas

7. Plot the following signal over βˆ’10 ≀ 𝑑 ≀ 10. Is the sum signal still periodic?

If so what is the period?

β€’ π‘₯1 (𝑑) = 1 + 1.5 π‘π‘œπ‘ (6 𝑑) βˆ’ 0.6 π‘π‘œπ‘ (4Ξ©0𝑑) Ξ©0 = πœ‹/10

Part D: Energy/Power of Signals

8. Energy of a signal over [βˆ’π‘‡

2, +

𝑇

2] is defined as 𝐸 = ∫ |π‘₯(𝑑)|2𝑑𝑑

+𝑇

2

βˆ’π‘‡

2

. The

power, on the other hand, is defined as 𝑃 =1

𝑇 ∫ |π‘₯(𝑑)|2𝑑𝑑

+𝑇

2

βˆ’π‘‡

2

. Find the energy

and power of the following signals over βˆ’10 ≀ 𝑑 ≀ 10 by using the symbol

operations of Matlab.

β€’ π‘₯(𝑑) = π‘’βˆ’|𝑑|

β€’ π‘₯(𝑑) = π‘’βˆ’π‘‘ cos(2πœ‹π‘‘) 𝑒(𝑑)

Part E: Shift/Scale/Reflect of Signals

9. For the following function plot π‘₯(𝑑), π‘₯(𝑑 βˆ’ 2), π‘Žπ‘›π‘‘ π‘₯(𝑑 + 2) in one figure

with different colors (assume βˆ’10 ≀ 𝑑 ≀ 10):

β€’ π‘₯(𝑑) = π‘’βˆ’|𝑑|

10. For each one of the following functions plot π‘₯(𝑑), π‘₯(2𝑑), π‘Žπ‘›π‘‘ π‘₯(0.5𝑑) in one

figure with different colors (assume βˆ’10 ≀ 𝑑 ≀ 10):

β€’ π‘₯(𝑑) = π‘’βˆ’|𝑑|

11. For each one of the following functions plot π‘₯(𝑑) π‘Žπ‘›π‘‘ π‘₯(βˆ’π‘‘) in one figure

with different colors (assume βˆ’10 ≀ 𝑑 ≀ 10):

β€’ π‘₯(𝑑) = 𝑑3

β€’ π‘₯(𝑑) = π‘’βˆ’0.2𝑑sin (𝑑)

II. Homework Assignments

Part A: Ramp/Unit Step Functions

1. Use ramp/ustep functions to create the following signals:

Page 92: Lab Manual - University of Arkansas

Part B: Even/Odd signals

2. Plot the even/odd parts of the following signal: (assume βˆ’10 ≀ 𝑑 ≀ 10)

β€’ 𝑦(𝑑) = 3 + r(t + 3) βˆ’ r(t βˆ’ 2) βˆ’ 6u(t βˆ’ 6)

Part C: Energy/Power of Signals

3. Calculate the energy and power of the following signal over βˆ’10 ≀ 𝑑 ≀ 10:

β€’ π‘₯(𝑑) = 2 cos2 (2πœ‹π‘‘ +πœ‹

4)

Part D: Shift/Scale/Reflect of Signals

Page 93: Lab Manual - University of Arkansas

4. Plot π‘₯(𝑑), π‘₯(2𝑑 βˆ’ 3), π‘Žπ‘›π‘‘ π‘₯(βˆ’2𝑑 + 1) for the following signal (assume

βˆ’10 ≀ 𝑑 ≀ 10):

β€’ π‘₯(𝑑) = 𝑑2sin (𝑑)

Page 94: Lab Manual - University of Arkansas

Lab 6 Linear System

I. Pre-lab

1. Calculate the following convolutions by-hand

A. )1()( tptp

B. )()()exp( tptpt

C. )()( tpttp

2. Repeat the example in Section II. Understand the Matlab program (bring the

Matlab script with you to the lab).

II. Example

The convolutional integral is approximated by using the Matlab function

conv(a,b), which calculates n

nbnmamy )()()( . We can get an approximation

of dhtxty )()()( as n

dtdtnhdtndtmxdtmy )()()( if the

sampling interval dt is small enough.

The following examples perform numerical convolution )()( tptp , where

otherwise,0

11,1)(

ttp , and compares the numerical result with the theoretical

results

The unit pulse function: upulse.m function y = upulse(x) % function y = upulse(x) % y = 1 if -1 <= x <= 1, % y = 0 otherwise %

% the number of elements in the vector x N_element = length(x);

% initialize y as an all zero vector y = zeros(1, N_element);

% if -1 <= x <= 1, then y = 1 one_idx_logic = and(x >= -1, x <= 1); y(one_idx_logic) = 1;

The main program: main.m

Page 95: Lab Manual - University of Arkansas

% This is the main file that performs the convolution clear all;

% sampling interval dt dt = 0.01;

% the time variable vector t = [-5:dt:5];

% signal x(t) x = upulse(t); % signal h(t) h = upulse(t);

% convolution between x(t) and h(t) y = conv(x, h, 'same')*dt;

% plot the convolution result plot(t, y)

% label the x-axis and y-axis xlabel('time (second)'); ylabel('y(t)'); % turn the grid on grid on;

% compare the numerical result with the theoretical result % calculating p(t) convolving with p(t) by hand, we have the % theoretical results as % y(t) = t+2, -2 <= t <= 0, % y(t) = -t+2, 0 <= t <= 2, % y(t) = 0, otherwise

% keep the original result hold on; % plot the theoretical result in the same figure t1 = [-2:dt:0]; plot(t1, t1+2, 'r--'); t2 = [0:dt:2]; plot(t2, -t2+2, 'r--');

legend('Numerical Result', 'Theorectical Result');

III. Lab Assignments

Part A: Convolutions

1. Use Matlab to perform numerical convolutions of the three questions in the

pre-lab. For each of the convolution:

1) Plot the numerical convolution results.

2) Plot, in the same figure as the numerical results, the theoretical

results based on your calculation.

Page 96: Lab Manual - University of Arkansas

Part B: Ideal Low Pass Filter

2. Consider a LTI system with impulse response )20(sinc20)( tth . It is an

ideal low pass filter with a cut-off frequency 10 Hz, that is, it will only allow

signals with frequency less than or equal to 10 Hz to pass through. We will

verify this low pass properties of the filter by passing sinusoidal signals at

different frequencies through it.

1) Plot )(th in the range of 1010 t with a sampling interval

.001.0dt Rescale the figure to show the result between the range

11 t (Use the Matlab function axis).

2) If the input )(1 tx is a sinusoidal signal with frequency 9 Hz, use

numerical convolution to find the output (use 1010 t and

.001.0dt ) Use subplot to plot the input and output of the system,

and rescale the figure with 11 t and .5.15.1 y Write

down the amplitude.

3) If the input )(2 tx is a sinusoidal signal with frequency 11 Hz, repeat

the above step.

4) If the input is )()( 21 txtxx , repeat the above step. Find the

frequency of the output signal by counting the number of cycles per

second.

5) Amplitude Response. Find the amplitudes of the output when the

input signal is a sinusoidal with frequencies 1 Hz. Repeat this

procedure for sinusoidal signals with frequencies 3:2:15 Hz,

respectively. Tabulate and plot the amplitudes as a function of the

frequency. This is the amplitude response of the LTI system.

Part C: Frequency and Music Notes

3. The frequencies of the music notes are given as follows

Table 1. Note Frequencies

Note C D E F G A B

Freq (Hz) 262 294 330 349 392 440 494

Each music note is a sinusoid signal with a certain frequency. The following

example shows how to play a music note with Matlab.

% sampling frequency is 100 KHz Fs = 100e3; % sampling interval Ts = 1/Fs Ts = 1/Fs;

Page 97: Lab Manual - University of Arkansas

% each note will be played for 0.5 second t = [0:Ts:0.5];

% The frequency for C note is 262 Hz Fc = 262;

% the sinusoidal signal with frequency Fc notec = cos(2*pi*Fc*t);

% play the sound sound(notec, Fs);

4. Write a Matlab program to play the following music piece:

CCGGAAG--, FFEEDDC--,

You can adjust the length of each note to get better result.

IV. Homework Assignments

Part A: Convolution

1. Calculate the following convolution both manually and with the Matlab

numerical convolution, and plot the theoretical and numerical results in the

same figure: )()()exp( tptpt .

Part B: Low Pass Filter

2. An RC circuit can be considered as a low pass filter: it allows low frequency

signal to pass through, and attenuates high frequency signal. The impulse

response of the circuit is )(exp1

)( tuRC

t

RCth

. Assume KR 1 ,

FC 20 . Following the same procedure as in Step 2(5), tabulate and plot

the amplitude response of the RC circuit at frequencies [1:2:21] Hz. (use

1010 t , 001.0dt , and measure the output amplitude in 11 t ).

Page 98: Lab Manual - University of Arkansas

Lab 7 Fourier Series

I. Pre-lab

1. Find the transfer function of the following RC circuit.

Fig. 1 an RC circuit

2. If the input to the above RC circuit is )2cos()( 0tftx = , find the output y(t).

3. Repeat the example in Section II. Understand the Matlab program (bring the

Matlab script with you to the lab).

II. Example

The following code calculates the Fourier series of the following signal with Matlab

symbolic calculation, with .1,50 == T

(Please note that the symbolic function for the unit step function u(t) in Matlab is

heaviside.)

Fig. 2 rectangular pulses

The Fourier Series function: FourierSeries.m function [X, w] = FourierSeries(x, T0, k_vec) % function [X, w] = FourierSeries(x, T0, k_vec) % % symbolically calculate the Fourier Series, and return the % numerical results % % x: the time domain signal within one period; % it must have definition over [0, T0] % it must be a symbolic function of t % % T0: the period of the signal

t

x(t)

Page 99: Lab Manual - University of Arkansas

% k_vec: the range of Harmonics to be calculated

syms t

for mm = 1:length(k_vec) k = k_vec(mm); % Fourier series X1(mm) = int(x*exp(-j*2*pi*k*t/T0), t, 0, T0)/T0 % change the symbolic value to numerical value X(mm) = subs(X1(mm)); % angular frequency w(mm) = k*2*pi/T0; end

The main program: main.m % main.m % Calculates the Fourier series through symbolic cacluations

clear all

% numerical Fourier Series syms t;

tau = 1; T0 = 5; k_vec = [-3:3];

% !!!IMPORTANT!!!: the signal definition must cover [0 to T0] % the signal is defined over [-T0, 2T0], which covers [0, T0] xt = heaviside(t+tau/2)-heaviside(t-tau/2) + heaviside(t-(T0-tau/2))-

heaviside(t-(T0+tau/2)); [Xw, w] = FourierSeries(xt, T0, k_vec);

% plot the results from Matlab calculation stem(w,abs(Xw), 'o-'); hold on;

% the results based on manual calculation (slides # 16) Xw_manual = tau/T0*sinc(k_vec*tau/T0); stem(w, abs(Xw_manual), 'r--');

legend('Matlab calculation', 'Manual calculation'); xlabel('\omega (rad/sec)'); ylabel('|c_k|');

III. Lab Assignments

Part A: Symbolic Fourier Series Calculation

1. Use Matlab to perform symbolic Fourier series calculation of the following

signals. Plot both the amplitude and phase of the harmonics. Plot in the same

Page 100: Lab Manual - University of Arkansas

figure the results from both Matlab calculation and manual calculation (use

the manual calculation results from Assignment # 6, question 2).

Fig. 3 Fourier series calculation

Part B: Gibbs Phenomenon

Let nc be the Fourier series coefficients of )(tx . Define

tjnN

Nn

nN ectx 0)(

+

βˆ’=

= as a truncated version of the original signal. The

following code shows how to plot )(txN for the signal in Fig. 3(a).

% Plot Fig. 3(a) N = 99; n_vec = [-N:N]; T0 = 2; Omega0 = pi;

% the Fourier series coefficients Cn = zeros(size(n_vec)); % odd indexed component Cn(1:2:end) = 2./(j*n_vec(1:2:end)*pi); % even indexed component Cn(2:2:end) = 0;

dt = 0.01; t = [-3:dt:3];

xt = 0; for m = 1:length(n_vec) xt = xt + Cn(m)*exp(j*n_vec(m)*Omega0*t); end

2. Plot )(txN in Fig. 3 (b) and (c) as a function of time for N = 3, 9, 19, and 99.

Part C: Linear Time Invariant System with Periodic Inputs

Page 101: Lab Manual - University of Arkansas

For LTI systems with periodic inputs, the output can be calculated in two

ways: convolution, or transfer function. We will perform both operations in

this part of the lab, and compare their results.

3. Input: )2cos()( 0tftx =

(a) Use convolution to find the output of the RC circuit in Fig. 1, tabulate

and plot the amplitude response of the RC circuit at frequencies [1:10:100]

Hz.

(use 11 βˆ’ t , 01.0=dt , and measure the output amplitude in 11 βˆ’ t ).

Refer to Lab 4 for procedures.

(b) Use transfer function to find the output of the RC circuit in Fig. 1,

tabulate and plot the amplitude response of the RC circuit at frequencies

[1:10:100] Hz.

)()( 00 =

+

βˆ’=

nHectytjn

n

n

(c) Plot the amplitude and phase response of the RC transfer function.

IV. Homework Assignments

Part B: Gibbs Phenomenon

1. Repeat Step 2 for Fig. 3(b).

Part B: Linear Time Invariant System with Periodic Inputs

1. If the input to the RC circuit in Fig. 1 is the signal shown in Fig. 3(a), use

transfer function to find the output, and plot the results between t between [-

3:dt:3], where dt = 0.01. Use )(txN and N = 200 to approximate x(t).

Page 102: Lab Manual - University of Arkansas

Lab 8 Fourier Transform

I. Pre-lab

1. Consider an ideal band pass filter with the transfer function

++

βˆ’=

BB

rectrectH

00)(

, where 0 is the center frequency (in

rad/sec) of the pass band, and 02 Bis the bandwidth. Find the impulse

response h(t).

2. Read and understand the following example.

II. Example

The following code calculates the symbolic Fourier transform of the rectangular

function

=

trecttx )(

. The symbolic results are compared to the theorectical

result.

(Please note that the symbolic function for the unit step function u(t) in Matlab is

heaviside.)

The main program: main.m % use the Matlab function fourier.m to symbolically find the % fourier transform syms t w

tau = 1; % symbolic rect(t/tau) rect_sym = heaviside(t+tau/2)-heaviside(t-tau/2);

% sybmolic F[rect(t)] fourier_rect_sym = fourier(rect_sym);

% use subs( ) to get the numerical rect(t) t_vec = [-3:0.01:3]; rect_t = subs(rect_sym, t, t_vec); figure(1) plot(t_vec, rect_t); axis([-3 3 -0.1 1.1]); xlabel('t (sec)'); ylabel('x(t)');

% use subs( ) to get the numerical value of the Fourier transform w_vec = [-50:0.01:50]; fourier_rect_w = subs(fourier_rect_sym, w, w_vec); figure(2); % plot the amplitude subplot(2, 1, 1); plot(w_vec, abs(fourier_rect_w));

Page 103: Lab Manual - University of Arkansas

axis([-50, 50, -0.5 1.5]); xlabel('\omega (rad/s)'); ylabel('|X(\omega)|') % plot the phase subplot(2, 1, 2); plot(w_vec, phase(fourier_rect_w)); xlabel('\omega (rad/s)'); ylabel('phase (rads)')

% theorectical expression of the fourier transform fourier_rect_w_theo = tau*sinc(w_vec*tau/(2*pi)); % plot the amplitude subplot(2, 1, 1); hold on; plot(w_vec, abs(fourier_rect_w_theo), 'r--'); legend('symbolic', 'theorectical'); % plot the phase subplot(2, 1, 2); hold on; plot(w_vec,% phase(fourier_rect_w_theo), 'r--'); legend('symbolic', 'theorectical');

III. Lab Assignments

Part A: Symbolic Fourier Transform

1. Use Matlab to perform symbolic Fourier transform calculation of the

following signals. Plot both the amplitude and phase response. Plot in the

same figure the theoretical Fourier transform results (use the theoretical

results from the Fourier transform table).

(1) )()exp()(1 tuttx βˆ’=

(2) |)|exp()(2 ttx βˆ’=

(3) |)|exp()(3 tttx βˆ’=

Part B: Band Pass Filtering of Audio Signals

The following code shows an example of passing an audio signal through a

low pass filter with cutoff frequency 1500 Hz.

% read the file [data, Fs, Nbits]=wavread('female_voice.wav'); data = data(:, 1).'; % Fs: sampling frequency; Ts: sampling period Ts = 1/Fs;

% playback the corrputed sound sound(data, Fs);

Page 104: Lab Manual - University of Arkansas

% time vector t = [-10:Ts:10];

% cutoff of the low pass filter is 1500 Hz wb = 1500*2*pi;

% ideal low pass filter with cutoff frequency wb % fourier transform: rect(w/wb) ht = wb/(2*pi)*sinc(wb*t/(2*pi));

% input: data, LTI impulse response: ht, output: y = convolution

between data and ht y = conv(data, ht, 'same');

% normalize the processed sournd to avoid clipping y = y/max(abs(y)); % playback the processed sound sound(y, Fs);

1. Change the cutoff frequency of the low pass filter and see how it affects the

sound.

2. The file corrupted_male_voice.wav contains a male voice distorted by two tones

at 100 Hz and 6000 Hz, respectively. Based on the results in the pre-lab, design a

band pass filter with passband [250, 3750] Hz. What are the values of w0 and wB? 3.

Pass the corrupted sound through the band pass filter, and play the output of the

filter.

Part C: Low Pass Filter

4. Consider a system with transfer function 𝐻(πœ”) = π‘Ÿπ‘’π‘π‘‘ (πœ”

πœ”π‘“). The input signal is

π‘₯(𝑑) = 5𝑠𝑖𝑛𝑐 (5𝑑

πœ‹) + 10𝑠𝑖𝑛𝑐 (

10𝑑

πœ‹). Write convolution in Matlab to find the

signal, y(t), at the output of the filter for the following values of πœ”π‘“, and compare

the results with the theorectical results (you can find the theoretical results in HW

10). Use dt = 0.001 and t = [-10:dt:10].

a) πœ”π‘“ = 7 rad/sec

b) πœ”π‘“ = 3 rad/sec

IV. Homework

1. Repeat the question in Part C for πœ”π‘“ = 12.