You are on page 1of 19

JAYPEE UNIVERSITY OF ENGINEERING &

TECHNOLOGY, GUNA DEPARMENT OF


ELECTRONICS & COMMUNICATION Digital
Signal Processing Lab (14B17EC572)
B. Tech. (ECE)
Semester V
DSP Laboratory
Experiment # 1
Aim: Review
MATLAB

of

In this lab we would have a review of MATLAB and get started with working in its
wonderfully simple environment.
MATLAB,
which
stands
for
Matrix
Laboratory,
is a very powerful program for performing numerical and
symbolic calculations, and is widely used in science and engineering, as well as
in mathematics.

Prela
b
1. You are basically responsible for learning MATLAB language on your
own. So read this
Experiment carefully and try to do an example of your own for each
part on MATLAB.
2.

Solve all the exercises in this experiment.

3.

Inside the Documents>Matlab folder, make a new folder and give it


suitable name. Also create a word folder in your N-derive to save all the
programs and their results to prepare the lab record.

4.

From this moment, any file you will be asked to do in this course will
be saved in these folders.

Lab
What is
MATLAB?
A high-performance language for technical computing. Typical uses of MATLAB:

Mathematical computations.

Algorithmic development.

Model prototyping (prior to complex model development).

Data analysis and exploration of data (visualization).

Scientific and engineering graphics for presentation.

Complex analysis using MATLAB toolboxes (i.e.,statistics,

neural networks, fuzzy logic, H-infinity control, economics, etc.) .

DSP LABORATORY:
EXPERIMENT#1

Coordinator: Dr. Rahul


Pachauri

Basics of MATLAB

MATLAB is a technical language to ease scientific computations.

The name is derived from MATrix LABoratory .

It provides many of the attributes of spreadsheets and programming


languages.

DSP LABORATORY:
EXPERIMENT#1

Coordinator: Dr. Rahul


Pachauri

MATLAB is a case sensitive language (a variable named c is different


than another one called C).
In interactive mode MATLAB scripts are platform independent (good
for cross platform portability).
MATLAB works with matrices.
Everything MATLAB understands is a matrix (from text to large cell
arrays and structure arrays).

The MATLAB Environment

Command
Window

Curre
nt

Workspace

Folde
r

Command
History

Basic Components of the MATLAB Environment


MATLAB has the following basic window components:

Command Window
-

to execute commands in the MATLAB environment

Current Directory Window


-

to quickly access files on the MATLAB path

Figure Window
-

Workspace Window
-

to display graphical output from MATLAB code


to view variable definitions and variable memory allocations

Command History Window


-

displays all commands issued in MATLAB since the last


session (good for learning and verification)

Getting Started

When MATLAB starts the MATLAB prompt >> appears.


All MATLAB commands are executed from this prompt.
>>
2.3+4.2
ans =
6.5000

MATLAB assigns the result to variable name ans. A percent sign is


a comment and is ignored.
>>
1+2
ans =
3

Operators & Special Characters


Operat
or +

*
/
.*
^
.
:^
(
[) ]
.

,
;
=
%

Operation
Plus; addition operator.
Minus; subtraction operator.
Scalar and matrix multiplication operator.
division operator
Array multiplication operator.
Scalar and matrix exponentiation operator.
Array exponentiation operator.
Colon; generates regularly spaced elements and represents an entire
row
or column.
Parentheses;
encloses function arguments and array indices;
overrides enclosures
precedence.
Brackets;
array elements.
Decimal point.
Ellipsis; line-continuation operator.
Comma; separates statements and elements in a row.
Semicolon; separates columns and suppresses display.
Assignment (replacement) operator.
Comment operator: inserts comments in the program

General Commands
help
topic provides help on topic
who
list variables currently in the workspace
whos
lists variables currently in the workspace
with their size. what
lists m-, mat-, and mex.
files on the disk.
clear
clears the workspace, all
variables are removed clear x,y,z
clears only
variables x, y and z
clear all
clears all variables and functions from workspace
clc
clears command window, command
history is lost. clf
clears figure window
cd
change the current
working directory dir
list
contents of the current directory mkdir
creates a directory

Never use a variable with the same name as a MATLAB function or


command. If you do so, that function or command will become
inaccessible.

Never create an M-file with the same name as a MATLAB function or


command

Variables

MATLAB does not require any type declarations or dimension


statements

When MATLAB encounters a new variable name, it automatically


creates the variable and allocates the appropriate amount of storage.

price_mango = 15
creates a 1 - by - 1 matrix named price_mango and stores the value
15 in its single
element.

Variable name consist of a letter, followed by any number of


letters, digits, or underscores. MATLAB uses only the first 63
characters of a variable name.

MATLAB is case sensitive; it distinguishes between upper case and


lowercase letters.
Reserved (Keyword) word list - for, end, if, while, function,
return, elseif, case, otherwise, switch, continue, else, try, catch,
global, persistent, break etc.

Numbers

MATLAB uses conventional decimal notation, with an optional


decimal point and leading plus or minus sign.

Scientific notation uses the letter e to specify a power-of- ten scale


factor

Imaginary numbers use either or as a suffix.

All numbers are stored internally using the long format specified by
the IEEE floating
point standard. Floating point numbers have a finite precision
of roughly 16 significant decimal digits and a finite range of roughly
-308
+308
10
to 10

Examples of legal numbers:

3,

99,

0.0001,

9.6412,

1.2 10,

6.2 11,

1,

3.15,

65

Complex Numbers: MATLAB recognizes the litters and as the


1. A
complex
imaginary number
number 2 + 5 may be input as 2 + 5 or 2 + 5 in MATLAB. The former case is
always interpreted as
a complex number whereas the later case is taken as complex only if has not been
assigned any local
value. The same is true for .

Display Formats
Display of numeric value of using different formats
MATLAB
Commands
format short
format long
format short e
format long e
format hex
format bank
format +
format rat

Displayed value of
3.1416
3.141592653589793
3.1416e+000
3.141592653589793
e+000
400921fb54442d18
3.14
+
355/113

Comments
Default display in five digits
Maximum 16 digits can be
displayed
5 digit plus exponent
16 digit plus exponent
Hexadecimal
2 decimal places
Positive only, negative 0
Ratio of whole numbers
(fraction)

MATLAB File Saving


MATLAB take .m extension in the file name and following are the Dos and Donts
for the file name:Dos
Lower case letters a to z
Upper case letters A to Z
Numerals 0 to 9

_ underscore

Donts
Keywords of MATLAB e.g. sum , randn, end, etc.
Special characters e.g. @, $, !, ., ( ) etc.
Start with numerals e.g. 2_ab is illegal file name
Space between letters/numerals e.g. a 2b is
illegal file name

Matrices and Vectors


To enter a matrix in MATLAB, use square brackets and separate entries within
a row by spaces or colon and separate rows using semicolons.
>> A = [2 1 -1 8; 1 0 8 -3;
7 1 2 4] A =
2 1 -1 8
1 0 8 -3
7 1 2 4

Often we do not want MATLAB to display a response, especially when


dealing with very large matrices. To suppress the output, place a semicolon at
the end of the line. Typing

>> B = [2 0 -3; -1 1 3];

To view the contents of the variable B just type its name.


>>
BB
=
2
-1

0
1

-3
3

Vectors (column vectors) are simply matrices with a single column.


>> v = [ 2; 3; -4]
v=
2
3
-4
A row vector is a matrix with a single row.
>> w = [3 -2 5 11]
w=
3 -2
5
11

It is often necessary to define vectors with evenly spaced entries. In MATLAB,


the colon (:) provides shorthand for creating such vectors.

>>
2:5
ans
=
2

3
5

Typing j:i:k defines a row vector with increment i starting at j and ending at k.
>>
3:2:9
ans =
3
5

In MATLAB, A' represents the transpose of the matrix A.


>> A=[5 -2 9;
11 7 8] A =
5 -2
9
11
7
8
>>
A'

ans
=
5 1
-2 17
9 8

The entry in row i, column j of a matrix A is A (i,j).


>> A = [3 -2 7 8; 4 3 2 1;
10 15 -2 9] A =
3
-2
7
8
4
3
2
1
10 15 -2
9
>>
A(3,2)=15

It is also possible to view multiple entries within any row or column. For
instance, the second and fourth entries in the third row are accessed as
follows.

>> A(3,[2 4])


ans =
15
9

Row i of A is A(i,:) and column j of A is A(:,j).

>>
A(3,:)
ans =
10 15
>>
A(:,3)
ans =
7
2
-2

-2

Next we display the first, second and fourth columns.


>> A(:,[1 2
4])
ans =
3 -2
8
4
3
1
10 15
9

To remove rows or columns from a matrix, simply redefine them to be empty


matrices.
>> A. =[ 4 7 2 1 3; 8 7 12 -2 5;
11 1 14 -2
= 1 3
4 0]7 A 2
8 7 12 -2 5
11 1 14 -2 0
>>
A(2,:)=[ ]
A=
4
7
2
1
3
11
1 14 -2
0
>> A(:,[1
3])=[ ] A =
7
1
3
1 -2
0
There are a number of special matrices that can be defined:
null matrix:
M = [ ];
nxm matrix of
zeros:

M=

nxm matrix of
ones:

M=

zeros(n,m);
ones(n,m);

nxn identity
matrix:

M = eye(n);

Uniformly distributed random elements M = rand(n,m);


Normally distributed random elements

M=randn(n,m);

But there is a better way. The colon by itself refers to all the elements in a row or
column of a matrix and the keyword end refers to the last row or column. So
sum(A(:,end)) %computes the sum of the elements in the last column of A.

Dimension Functions
Dimensioning is automatic in MATLAB. You can find the dimensions of an existing
matrix with the
size. Also the command length(x) returns the length of the vector x
>> X=[1 2 3;6 7 8]
>> [m,n] = size(X)

% returns the size of matrix X in separate variables m and n.

>> x = ones(1,8);
>> n = length(x)

% will assign the value 8 to n

Concatenat
ion:
Concatenation is the process of joining small matrices to make bigger
ones. In fact, you made your first matrix by concatenating its individual
elements. The pair of square brackets, [ ], is the concatenation operator. To do
so horizontally, we separate the arrays with spaces or commas:
>> [ones(2,3), zeros(2,3)]
To do so vertically, we separate the arrays with a semicolon:
>> [ones(2,3); zeros(2,3)]

Functions for Complex Numbers


Command

This returns the

complex(x,y)

Return a complex number x+yi

real(x)

real part of a complex number

imag(x)

imaginary part of a complex number

abs(x)

magnitude of the complex number

angle(x)

angle of a complex number x

conj(x)

complex conjugate of the complex number x

cart2pol

Convert Cartesian to Polar form of complex number

pol2cart

Convert Polar to Cartesian form of complex number

Control Flow Statements


Relations
The relational operators in MATLAB are:
<
Less than
>
Greater than
<=
less than or equal
>=
greater than or equal
==
Equal
~=
not equal
Note that = is a direct assignment while = = is the logical equal. Relations
may be connected or quantified by the logical operators
&
|
~

and
or
not

Variable Controlled for Loop


The general form is
for variable = first: inc: last
statements
end

If the increment inc is not specified, a default value of 1 is used. For example

x=[ ];
for i=1:4
x=[x,i^2]
end
x=
1
x=
1
4x=
4
1
x=
4
1

9
9 16

Branching if Loop
if relation
true alternative
els
false alternative
e
en
d
if

1>
2
a=
1
else
a=
2
en
da
=
2

Graphics in
MATALB:
Creating a Plot
The plot function has different forms, depending on the input arguments.
If y is a vector,
plot(y) produces a piecewise linear graph of the elements of y versus the index
of the elements of
y. If you specify two vectors as arguments, plot(x,y) produces a graph of y versus
x.
DSP LABORATORY:
EXPERIMENT#1

10

Coordinator: Dr. Rahul


Pachauri

For example, these statements use the colon operator to create a vector of x
values ranging from
zero to 2, compute the sine of these values, and plot the result.
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
%Now label the axes and add a title. The characters \pi create the symbol .
xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the Sine Function','FontSize',12)

DSP LABORATORY:
EXPERIMENT#1

11

Coordinator: Dr. Rahul


Pachauri

Multiple Data Sets in


One Graph
Multiple x-y pair arguments create multiple graphs with a single call to plot.
MATLAB automatically cycles through a predefined list of colors to allow
discrimination among sets of data. For example, these statements plot three
related functions of x, each curve in a separate distinguishing color.
x= 0:pi/40:2*pi;
y= sin(x);
y2 = sin(x-0.25);
y3 = sin(x-0.5);
plot(x,y,x,y2,x,y3)
legend('sin(x)','sin(x-.25)','sin(x-.5)')
% The legend command provides an easy way to identify the individual plots.
1

sin(x )
sin(x
-.25)
sin(x -.5)

0.8

0.6
0.4

0.2

-0.2
-0.4

-0.6
-0.8
-1

Axis rescaling:
MATLAB provides automatic scaling. The command axis([xmin. xmax. ymin.
ymax.]) enforces the manual scaling. For example
axis([-10 40 -inf inf])
produces an x-axis scale from - 10 to 40 and an automatic scaling for the y-axis
scale. Typing axis
again or axis(auto) resumes auto scaling.

Stem
If you wish to use information in discrete-time using the stem command can
be useful. It is very similar to plot except it doesnt connect the dots.
The following example creates a stem plot of a cosine function.
y = linspace(0,2*pi,10);
h = stem(cos(y),'fill','-.');
set(h(3),'Color','r','LineWidth',2) % Set base line
properties axis ([0 11 -1 1])

Specifying Line
and Colors

Styles

It is possible to specify color, line styles, and markers (such as plus signs or
circles) when you plot your data using the plot command.
plot(x,y,'color_style_marker') , where color_style_marker is a string containing
from one to four characters (enclosed in single quotation marks)
constructed from a color, a line style, and a marker type:

Color strings are 'c', 'm', 'y', 'r', 'g', 'b', 'w', and 'k'. These
correspond to cyan, magenta, yellow, red, green, blue, white, and
black.

Linestyle strings are '-' for solid, '--' for dashed, ':' for dotted, '-.' for
dash-dot.
Omit the linestyle for no line.

The marker types are '+', 'o', '*', and 'x' and the filled marker
types are 's' for square, 'd' for diamond, '^' for up triangle, 'v'
for down triangle, '>' for right triangle, '<' for left triangle, 'p'
for pentagram, 'h' for hexagram, and none for no marker.

Adding Plots to an Existing Graph


The hold command enables you to add plots to an existing graph. When you type
hold on
MATLAB does not replace the existing graph when you issue another plotting
command; it adds the new data to the current graph, rescaling the axes if
necessary. To remove the effect of the hold on function you may use:
hold off

Multiple Plots in One Figure


The subplot command enables you to display multiple plots in the same window
or print them on the same piece of paper. Typing:
subplot(m,n,p)
partitions the figure window into an m-by-n matrix of small subplots and
selects the pth subplot for the current plot. The plots are numbered along first
the top row of the figure window, then the second row, and so on. For example,
these statements plot data in four different subregions of the figure window.
t = 0:pi/10:2*pi;
[X,Y,Z] = cylinder(4*cos(t));
subplot(2,2,1); mesh(X)
subplot(2,2,2); mesh(Y)
subplot(2,2,3); mesh(Z)
subplot(2,2,4); mesh(X,Y,Z)

Figure
Windows
Graphing functions automatically open a new figure window if there are
no figure windows already on the screen. If a figure window exists, MATLAB
uses that window for graphics output. If there are multiple figure windows
open, MATLAB targets the one that is designated the current figure (the last
figure used or clicked in).
To make an existing figure window the current figure,
you can type :
>> figure(n)
where n is the number in the figure title bar. The results of subsequent
graphics commands are displayed in this window. To open a new figure window
and make it the current figure, type:
>> figure

Exerc ise#1
(a) Generate a matrix of size 5x5 of normally distributed
rd

random numbers. (b) Change the value of the 3 row to [8 7


3 2 4].

Exerc is
e#2

(c) Delete the 2

nd

column.

(a) Start with the 4-by-4 square, A.


(b) Then form B = [A A+32; A+48 A+16]

Exerc is
e#3

(c) Whats the size of B? Also find the size of B without semicolon
(;).

Define the following discrete time signal using zeros and ones functions
and plot using stem
function.

= )(
Exerc is
e#4

0.8
0
0.2

0 < 10
10 < 20
20

0
Generate and plot 100 samples of the following signals using inspace
function. Label the axiss suitably. Give suitable title to the plots. Use grid on
function in plots. Plot real and imaginary parts of
signal () and use legend function to identify them. Also show 3-D plot of signal ().

Show all three


plots on same figure using subplot function.
( ) ( 0.2 ) 2 + ( 0.1 ) 4 = ()

Exerc is
e#5

() 10 = ( )

5 5

0.02 =

Using MATLAB, plot the 610 samples of function


( = )

cos(8

)
where,
t ranges
from 1 to 5. Give the x-axis the title (t sec) and the y-axis the
title (f(t)
volts ).
Repeat using stem function. Then use subplot to combine the two figures
in one figure and
give it the name: difference between plot and stem. Use axis command to show
plots in the range
[-3, 12, -10, 10]

You might also like