lab manual - university of arkansas
TRANSCRIPT
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)
Department of Electrical EngineeringUniversity of Arkansas
A Tutorial on Matlab
Ch. 1 Introduction
Dr. Jingxian Wu
OUTLINE
2
β’ Introduction: what is Matlab?
β’ Basics
β’ Simple Arithmetic
β’ Matlab workspace
β’ Getting help
β’ Exercises
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)
INTRODUCTION
β’ Application areas
β Engineering
β Science
β Biomedical
β Economics
β β¦β¦
OUTLINE
5
β’ Introduction: what is Matlab?
β’ Basics
β’ Simple arithmetic
β’ Matlab workspace
β’ Getting help
β’ Exercises
BASICS
Enter Matlab command here
Matlab command window
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
BASICS
β’ Variablesβ We can assign values to variables
β Examples
>> x = 3
x =
3
>> y = 5
y =
5
>> x+y*2
ans =
13
>>
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
>>
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
>>
OUTLINE
11
β’ Introduction: what is Matlab?
β’ Basics
β’ Simple arithmetic
β’ Matlab workspace
β’ Getting help
β’ Exercises
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
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
SIMPLE ARITHMETIC
β’ Example:
β Use Matlab to evaluate the expression:
β y= exp βπ + cos π log π
β where π = β2 + 3π, π =3π
5, π = 10
OUTLINE
15
β’ Introduction: what is Matlab?
β’ Basics
β’ Simple Arithmetic
β’ Matlab workspace
β’ Getting help
β’ Exercises
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
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
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:
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
OUTLINE
20
β’ Introduction: what is Matlab?
β’ Basics
β’ Simple Arithmetic
β’ Matlab workspace
β’ Getting help
β’ Exercises
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
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
β¦
OUTLINE
23
β’ Introduction: what is Matlab?
β’ Basics
β’ Matlab workspace
β’ Getting help
β’ Exercises
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)
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.
Department of Electrical EngineeringUniversity of Arkansas
A Tutorial on Matlab
Ch. 2 Matrix Operations
Dr. Jingxian Wu
OUTLINE
2
β’ Vectors
β’ Matrices
β’ Matrix operations
β’ Exercises
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)
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
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
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
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
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
OUTLINE
9
β’ Vectors
β’ Matrices
β’ Matrix operations
β’ Exercises
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
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
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)
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
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
OUTLINE
15
β’ Vectors
β’ Matrices
β’ Matrix operations
β’ Exercises
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
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
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
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
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
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
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
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
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
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
OUTLINE
26
β’ Vectors
β’ Matrices
β’ Matrix operations
β’ Exercises
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?
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
Department of Electrical EngineeringUniversity of Arkansas
A Tutorial on Matlab
Ch. 3 Programming in Matlab
Dr. Jingxian Wu
OUTLINE
2
β’ Plotting
β’ M-file Scripts
β’ Functions
β’ Control Flows
β’ Exercises
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
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
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
OUTLINE
6
β’ Plotting
β’ M-file Scripts
β’ Functions
β’ Control Flows
β’ Exercises
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
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
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
OUTLINE
10
β’ Plotting
β’ M-file Scripts
β’ Functions
β’ Control Flows
β’ Exercises
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
FUNCTIONS
β’ Call the function
β In the command window
>> x = 1:10;
>> y = average(x)
>> z = sqrt(x);
>> average(z)
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;
OUTLINE
14
β’ Plotting
β’ M-file Scripts
β’ Functions
β’ Control Flows
β’ Exercises
CONTROL FLOWS
β’ Matlab control flows:
β 1. if β¦ elseif β¦ else β¦ end
β 2. for β¦ end
β 3. while β¦ end
CONTROL FLOWS
β’ if β¦ end
x = 10;
y = sqrt(x)-x/3;
if y < 0
'y is less than 0'
y = y + 1;
end
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
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
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;
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;
CONTROL FLOWS
β’ while β¦ end
x = 1;
while x <= 20
x = 3*x+2;
end
OUTLINE
22
β’ Plotting
β’ M-file Scripts
β’ Functions
β’ Control Flows
β’ Exercises
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
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
Department of Electrical EngineeringUniversity of Arkansas
A Tutorial on Matlab
Ch. 4 Symbolic Operations
Dr. Jingxian Wu
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
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 β=)(
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 β=)(
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
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
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 β=)(
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
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
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].
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.
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
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:
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
4. Plot π₯(π‘), π₯(2π‘ β 3), πππ π₯(β2π‘ + 1) for the following signal (assume
β10 β€ π‘ β€ 10):
β’ π₯(π‘) = π‘2sin (π‘)
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
% 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.
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;
% 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 ).
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)
% 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
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
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).
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));
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);
% 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.