You are on page 1of 12

American International University-Bangladesh

Department of Electrical and Electronic Engineering


Digital Signal Processing

Experiment no. 01

Experiment Name: Introduction to MATLAB

Abstract:

MATLAB is a very useful and widely used tool in numerous divisions of engineering. In
Digital Signal Processing, MATLAB is an integral part. It plays an important role in
analyzing and performing various operations on signal processing.

Introduction:

The purpose of this experiment is to gain familiarity with MATLAB and build some
basic skills in MATLAB language. The very basics of MATLAB, i.e. writing codes,
computing mathematical calculations, the concept of arrays, plotting data, creating
functions etc. are described in this experiment.

Theory & Methodology:

MATLAB is a high-performance language for technical computing. The name MATLAB


stands for MATRIX LABORATORY. In Academic environment, it is the standard
instructional tool for introductory and advanced courses in mathematics, engineering
and science. There are some basic characters descriptions explained in the table below
which are commonly using in MATLAB.

Table 1: Arithmetic operators and special characters

Character Description

+ Addition
− Subtraction
* Multiplication (scalar and array)
/ Division (right)
ˆ Power or exponentiation
: Colon; creates vectors with equally spaced elements Semi-
; colon; suppresses display; ends row in array Comma;
, separates array subscripts
... Continuation of lines
% Percent; denotes a comment; specifies output format Single
quote; creates string; specifies matrix transpose Assignment
= operator
() Parentheses; encloses elements of arrays and input arguments
[] Brackets; encloses matrix elements and output arguments

1
Table 2: Array operators

Character Description

.* Array multiplication
./ Array (right) division
.ˆ Array power
.\ Array (left) division
.’ Array (nonconjugated) transpose

Table 3: Relational and logical operators

Character Description

< Less than


≤ Less than or equal to
> Greater than
≥ Greater than or equal to
== Equal to
& Logical or element-wise AND
| Logical or element-wise OR
&& Short-circuit AND
|| Short-circuit OR

Table 4: Managing workspace and file commands

Command Description

cd Change current directory


clc Clear the Command Window
clear (all) Removes all variables from the workspace
clear x Remove x from the workspace
copyfile Copy file or directory
delete Delete files
dir Display directory listing
exist Check if variables or functions are defined
help Display help for MATLAB functions
lookfor Search for specified word in all help entries
mkdir Make new directory Move
movefile file or directory Identify
pwd current directory Remove
rmdir directory
type Display contents of file
what List MATLAB files in current directory
which Locate functions and files
who Display variables currently in the workspace
whos Display information on variables in the workspace
2
Table 5: Predefined variables and math constants

Variable Description

ans Value of last variable (answer) Floating-


eps point relative accuracy Imaginary unit
i of a complex number
Inf Infinity (∞)
eps Floating-point relative accuracy
j Imaginary unit of a complex number
NaN Not a number
pi The number π (3.14159 . . .)

Table 6: Elementary matrices and arrays

Command Description

eye Identity matrix


linspace Generate linearly space vectors
ones Create array of all ones
rand Uniformly distributed random numbers and arrays
zeros Create array of all zeros

Table 7: Arrays and Matrices: Basic information

Command Description

disp Display text or array


isempty Determine if input is empty matrix
isequal Test arrays for equality
length Length of vector Number
ndims of dimensions Number of
numel elements Size of matrix
size

3
Table 8: Arrays and Matrices: operations and manipulation

Command Description

cross Vector cross product


diag Diagonal matrices and diagonals of matrix
dot Vector dot product
end Indicate last index of array
find Find indices of nonzero elements
kron Kronecker tensor product
max Maximum value of array Minimum
min value of array
prod Product of array elements
reshape Reshape array
sort sum Sort array elements Sum
size of array elements Size of
matrix

Table 9: Arrays and Matrices: matrix analysis and linear equations

Command Description

cond Condition number with respect to inversion


det Determinant
inv Matrix inverse
linsolve Solve linear system of equations
lu LU factorization Matrix
norm or vector norm Null
null space Orthogonalization
orth Matrix rank
rank Reduced row echelon form
rref Sum of diagonal elements
trace

Pre-Lab Homework:
Install MATLAB and go through the basics. As a preparation for your DSP Lab session,
start Matlab on any computer that has Matlab installed, type "helpdesk", click on
"Getting Started" and read topics.

Apparatus:
 Computer (Desktop/Laptop)
 MATLAB (at least version 6)

Precautions:Make sure that all the m-files are saved in the current directory of
MATLAB. Otherwise, the m-files will not be found and executed when they are called
from the command window.
4
Experimental Procedure: (corresponding simulation & Measurement numbers as well as
Codes are given in Appendices section using same number)
1. Find where xx= sin( ). Store the result in yy.
2. Find conjugate, absolute value, angle , real, imaginary parts of a complex number
zz=3+4i.
3. Plot real and complex numbers.
4. Learn use of colon to create different types of array of numbers.
5. Extract or insert numbers in arrays.
6. Work with vectors.
7. Creating script file – funky.m , run the commands in the file & type out the
contents of funky.m to the screen.
8. Create a function to generate a cosine wave named cosgen. Input parameters are
desired frequency and duration of waveform in seconds.
9. Create a Function to add and multiply two complex numbers.
10. Create a Function to generate a matrix Z with identical columns equal to an input
vector xx . Input parameters are vector and no. of desired columns.
11. Generate a random numbers matrix , it will replace all the negative numbers of
that matrix by 0.
12. Generate a function that replaces the negative elements of a matrix with the
number 77.

Simulation & Measurement:

1. yy = 0.8090
2. zz =
3.0000 + 4.0000i
ans =
3.0000 - 4.0000i
ans =5
ans = 0.9273
ans =3
ans =4
3. Both real and complex number plots will be as follows:
18

16

14

12

10

-2
-3 -2 -1 0 1 2 3

5
4.
jkl =
2 6 10 14
jkl =
99 98 97 96 95 94 93 92 91 90 89 88
ttt =
Columns 1 through 13
2.0000 2.1111 2.2222 2.3333 2.4444 2.5556 2.6667 2.7778 2.8889
3.0000 3.1111 3.2222 3.3333
Columns 14 through 19
3.4444 3.5556 3.6667 3.7778 3.8889 4.0000
tpi =
Columns 1 through 13
6.2832 5.9341 5.5851 5.2360 4.8869 4.5379 4.1888 3.8397 3.4907
3.1416 2.7925 2.4435 2.0944
Columns 14 through 19
1.7453 1.3963 1.0472 0.6981 0.3491 0
5. a)
xx =
1 1 1 1 2 4 6 8 10 0 0 0
ans =
1 1 2 4 6
ans =
12
ans =
1 1 4 8 0 0
b)
xx =
1.0000 1.0000 3.1416 6.2832 9.4248 12.5664 15.7080 8.0000 10.0000
0 0 0
6. a)
kset =
-3 -2 -1 0 1 2 3 4 5 6 7 8 9 10 11
ans =
Columns 1 through 13
-0.7071 0.0000 0.7071 1.0000 0.7071 0.0000 -0.7071 -1.0000 -0.7071
-0.0000 0.7071 1.0000 0.7071
Columns 14 through 15
0.0 -0.7071

b)
xx =
0
xx =
0 0.7071
xx =
0 0.7071 1.0000
xx =
0 0.7071 1.0000 0.7071
6
xx =
0 0.7071 1.0000 0.7071 0.0000
xx =
0 0.7071 1.0000 0.7071 0.0000 -0.7071
xx =
0 0.7071 1.0000 0.7071 0.0000 -0.7071 -1.0000
xx =
0 0.7071 1.0000 0.7071 0.0000 -0.7071 -1.0000 -0.7071

7.
TEST PLOT of SINUSOID
1

0.8

0.6

0.4

0.2

-0.2

-0.4

-0.6

-0.8

-1
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2 2.5 3
TIME (sec)

Running script files from MATLAB:


tt = -2 : 0.05 : 3;
xx = sin( 2*pi*0.789*tt );
D:\Work\MATLABinstalled\bin\funky.m

11.
A=

0.0859 0.7481 0.4882


-1.4916 -0.1924 -0.1774
-0.7423 0.8886 -0.1961
-1.0616 -0.7648 1.4193
2.3505 -1.4023 0.2916
-0.6156 -1.4224 0.1978
A=
0.0859 0.7481 0.4882
0 0 0
0 0.8886 0
0 0 1.4193
2.3505 0 0.2916
0 0 0.1978

7
Results and Discussion:

The codes were written on the command window and m-file. Functions were written in m-file
and called from command window and their responses have been observed.

Conclusion:

In this experiment, a detailed introduction to MATLAB was given. The interface of


MATLAB and the basic building blocks were discussed. After the completion of this lab,
students were able to understand the structure of the software and will be able to write codes,
plotting graphs, making functions and compute simple and complex mathematical
computations.

Exercises: Using MATLAB

The following exercise can be completed at your convenience. Results from each part should
be included in a brief lab report write-up.

Manipulating Sinusoids with MATLAB


Generate two 3000 hertz sinusoids with different amplitudes and phases.

x1(t) = A1 cos(2π(3000)t + j1) x2(t) = A2 cos(2 π(3000)t + j2)

(a) Select the value of the amplitudes as follows: let A1 = 13 and use your age for A2. For the
phases, use the last two digits of your telephone number for j1 (in degrees), and take j2 =30º.
When doing computations in Matlab, make sure to convert degrees to radians.
(b) Make a plot of both signals over a range of t that will exhibit approximately 3 cycles.
Make sure the plot starts at a negative time so that it will include t = 0, and make sure
that your have at least 20 samples per period of the wave.
(c) Verify that the phase of the two signals x1(t) and x2(t) is correct at t = 0, and also verify
that each one has the correct maximum amplitude.
(d) Use subplot(3,1,1) and subplot(3,1,2) to make a three-panel subplot that puts both of
these plots on the same window. See help subplot.
(e) Create a third sinusoid as the sum: x3(t) = x1(t) + x2(t). In Matlab this amounts to
summing the vectors that hold the samples of each sinusoid. Make a plot of x3(t) over the
same range of time as used in the previous two plots. Include this as the third panel in the
window by using subplot(3,1,3).
(f) Measure the magnitude and phase of x3(t) directly from the plot. In your lab report,
explain how the magnitude and phase were measured by making annotations on each of
the plots.

Lab Review Questions


In general, your lab write-up should indicate that you have acquired a better understanding of
the topics treated by the laboratory assignment. Here are a few questions for you to answer in
order to assess your understanding of this lab's objective: a working knowledge of the basics
of Matlab. If you do not know the answers to these questions go back to the lab and try to
figure them out in Matlab (remember the commands help and lookfor).

1. You saw how it easy it is for Matlab to generate and manipulate vectors (i.e., 1-
8
dimensional arrays of numbers). For example, consider the following:
yy = 0:10;
yy = zeros(1,25);
yy = 1:.25:5;
(a) How would you modify one of the above lines of Matlab code to create a vector that
steps from 0 to 10 in steps of .
(b) How would you modify one of the lines in the code to create a vector of one hundred
100's?
2. You also learned that Matlab has no problem handling complex numbers . Consider the
following line of code:
yy = 3 + 5j;
(a) How do you get Matlab to return the magnitude of the complex number yy?
(b) How do you get Matlab to return the phase of the complex number yy? What are
the units of the answer?
3. You learned that multiple lines of Matlab code can be stored in a file with a .m extension.
Matlab then executes the code in the order that it appears in the file.
Consider the following file, named example.m:
f = 200;
tt = [0:1/(20*f):1];
z = exp(j*2*pi*f*tt);
subplot(211)
plot(real(z))
title('Real part of exp(j*2*pi*200*tt)')
subplot(212)
plot(imag(z))
title('Imaginary part of exp(j*2*pi*200*tt)')

(a) How do you execute the file from the Matlab prompt?
(b) Suppose the file were named example.dog. Would it run? How could you change it to
make it work in Matlab?
(c) Assuming the M-file runs, what do you expect the plots to look like? If you're not sure
type in the code and run it.

Reference:
[1] John G. Proakis, and Dimitris G. Manolakis, Digital Signal Processing, New Delhi,
Prentice Hall of India, 2003.

[2] http://www.math.mtu.edu/~msgocken/intro/intro.html

Appendices:
[Basic Commands:
help
help plot
help colon
help ops
help zeros
help ones
lookfor filter]

9
1. xx = sin( pi/5 );
yy = sqrt( 1 - xx*xx )
ans
2. zz = 3 + 4i
conj(zz)
abs(zz)
angle(zz)
real(zz)
imag(zz)
3. xx = [-3 -1 0 1 3 ];
yy = xx.*xx - 3*xx;
plot( xx, yy ) % Real number plot
zz = xx + yy*sqrt(-1);
plot( zz ) % complex number plot
4. jkl = 2 : 4 : 17
jkl = 99 : -1 : 88
ttt = 2 : (1/9) : 4
tpi = pi * [ 2 : (-1/9) : 0 ]
5. a)
xx = [ ones(1,4), [2:2:11], zeros(1,3) ]
xx(3:7)
length(xx)
xx(2:2:length(xx))

b)
xx(3:7) = pi*(1:5)
6. a)
kset = -3:11;
kset
cos( pi*kset/4 )
b)
xx = [ ]; %<--- initialize the x vector to a null
for k=0:7
xx(k+1) = sin( k*pi/4 ) %-- xx(0) would fail
end
7. tt = -2 : 0.05 : 3;
xx = sin( 2*pi*0.789*tt );
plot( tt, xx ), grid on %<--- plot a sinusoid
title('TEST PLOT of SINUSOID')
xlabel('TIME (sec)')
Running scripts from MATLAB:
funky %<---will run the commands in the file
type funky %<---will type out the contents of
% funky.m to the screen
which funky
8. function xx = cosgen(f,dur)
%COSGEN Function to generate a cosine wave
% usage:
% xx = cosgen(f,dur)
10
% f = desired frequency
% dur = duration of the waveform in seconds
%
tt = [0:1/(20*f):dur]; % gives 20 samples per period
yy = cos(2*pi*f*tt);
9. function [sum,prod] = sumprod(x1,x2)
%SUMPROD Function to add and multiply two complex numbers
% usage:
% [sum,prod] = sumprod(x1,x2)
% x1 = a complex number
% x2 = another complex number
% sum = sum of x1 and x2
% prod = product of x1 and x2
%
sum = z1+z2;
prod = z1*z2;
10. function Z = expand(xx,ncol)
%EXPAND Function to generate a matrix Z with identical columns
% equal to an input vector xx
% usage:
% Z = expand(xx,ncol)
% xx = the input vector containing one column for Z
% ncol = the number of desired columns
%
xx = xx(:); %-- makes the input vector x into a column vector
Z = zeros(length(xx),ncol);
for i=1:ncol
Z(:,i) = xx;
End
11. A = randn(6,3)
A = A .* (A>0)
12. function Z = replacez(A)
%REPLACEZ Function that replaces the negative elements
% of a matrix with the number 77
% usage:
% Z = replacez(A)
Page 6 of 7
% A = input matrix whose negative elements are to
% be replaced with 77
%
[M,N] = size(A);
for i=1:M
for j=1:N
if A(i,j) < 0
Z(i,j) = 77;
else
Z(i,j) = A(i,j);
end
end
11
end

12

You might also like