You are on page 1of 62

Digital Signal Processing :

Introduction to MATLAB

What is MATLAB
High level language for technical
computing
Stands for MATrix LABoratory

Everything is a matrix - easy to do


linear algebra

MATLAB Desktop
Menu and toolbar

Workspace

History

Command

MATLAB Windows

Command window: main window


characterized by >> command prompt.

Edit window: where programs are written


and saved as M-files.

Graphics window: shows figures,


alternately known as Figure window.

Matlab
Basics

MATLAB Basics: Variables

Variables:
-Variables are assigned numerical values
by typing the expression directly
>> a = 1+2
>> a =
3
>> a = 1+2;

press enter

suppresses the output

Interactive Commands

Enter commands at >> prompt

Variable x automatically allocated

MATLAB does not require declaration of


variables

Interactive Commands

MATLAB is case sensitive

Variable ans will take value


of result of command if no
equal sign specified

Holds most recent result only

Semicolon at end of line will


suppress output, it is not
required like in C

Useful in script files and


debugging

Interactive Commands

Format of output

Defaults to 4 decimal places


Can change using format statement
format long changes output to 15 decimal
places

Variables

MATLAB is case sensitive

X is not equal to x

Variable names must start


with a letter

Youll get an error if this


doesnt happen
After that, can be any
combination of letters,
numbers and underscores

No special characters though

Variables

Dont name your variables the same as


functions

min, max, sqrt, cos, sin, tan, mean, median,


etc
Funny things happen when you do this

MATLAB reserved words dont work either

i, j, eps, nargin, end, pi, date, etc


i, j are reserved as complex numbers initially

Will work as counters in my experience so they can


be redefined as real numbers

Variables

several predefined variables


i sqrt(-1)
j sqrt(-1)
pi 3.1416...

>> y= 2*(1+4*j)
>> y=
2.0000 + 8.0000i

BEIT, 6th Semester

MATLAB Basics:

Arithmetic operators:
+ addition,
- subtraction,
* multiplication,
/division,
^ power operator,
' transpose

BEIT, 6th Semester

Array, Matrix

a vector

x = [1 2 5 1]

x =
1

a matrix

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

x =
1
5
3

2
1
2

transpose

3
4
-1
y = x

y =
1
2
5
1

Long Array, Matrix

t =1:10
t =

2
3
4
k =2:-0.5:-1

k =

1.5

0.5

-0.5

= [1:4; 5:8]

x =
1
5

2
6

3
7

4
8

-1

10

Generating Vectors from


zeros(M,N) MxN matrix of zeros
functions
x = zeros(1,3)
x =
0

ones(M,N) MxN matrix of ones

rand(M,N) MxN matrix of


uniformly
distributed random
numbers on (0,1)

x = ones(1,3)
x =
1
1
1
x = rand(1,3)
x =
0.9501 0.2311 0.6068

Matrix Index

The matrix indices begin from 1 (not 0 (as in C))


The matrix indices must be positive integer

Given:

A(-2), A(0)
Error: ??? Subscript indices must either be real positive integers or
logicals.
A(4,2)
Error: ??? Index exceeds matrix dimensions.

Concatenation of Matrices

x = [1 2], y = [4 5], z=[ 0 0]


A = [ x y]
1

B = [x ; y]
1 2
4 5
C = [x y ;z]

Error:
??? Error using ==> vertcat CAT arguments dimensions are not consistent

Operators (arithmetic)
+ addition
- subtraction
* multiplication
/ division
^ power
complex conjugate transpose

Matrices Operations
Given A and
B:

Additio
n

Subtractio
n

Product

Transpose

Creating Matrices

zeros(m, n): matrix with all zeros

ones(m, n): matrix with all ones.

eye(m, n): the identity matrix

rand(m, n): uniformly distributed random

randn(m, n): normally distributed random

magic(m): square matrix whose elements

have the same sum, along the row,


column and diagonal.
pascal(m) : Pascal matrix.

Matrix operations

^: exponentiation

*: multiplication

/: division

\: left division. The operation A\Bis


effectively the same as INV(A)*B,

although left division is calculated


differently and is much quicker.
+: addition
-: subtraction

Array Operations

Evaluated element by element


.'
.^
.*
./

:
:
:
:

array
array
array
array

transpose (non-conjugated transpose)


power
multiplication
division

Very different from Matrix operations

>> A=[1 2;3 4];


>> B=[5 6;7 8];
>> A*B
19
22
43
50

But:

>> A.*B
5
21

12
32

Some Built-in functions

mean(A):mean value of a vector

max(A), min (A): maximum and minimum.

sum(A): summation.

sort(A): sorted vector

median(A): median value

std(A): standard deviation.

det(A) : determinant of a square matrix

dot(a,b): dot product of two vectors

Cross(a,b): cross product of two vectors

Inv(A): Inverse of a matrix A

Indexing Matrices
Given the matrix:

Then:

A =
0.9501

0.6068

0.4231

0.2311

0.4860

0.2774

A(1,2) = 0.6068

Aij ,i 1...m, j 1...n

A(3) = 0.6068

index (i 1)m j

A(:,1) = [0.9501
1:m

]
0.2311

A(1,2:3)=[0.6068

0.4231]

Adding Elements to a Vector or


a Matrix
>> A=1:3
A=
1 2 3
>> A(4:6)=5:2:9
A=
1 2 3 5 7
>> B=1:2
B=
1 2
>> B(5)=7;
B=
1 2 0

>> C=[1 2; 3 4]
C=
1 2
3 4
>> C(3,:)=[5 6];
C=
1 2
3 4
5 6

>> D=linspace(4,12,3);
>> E=[C D]
E=
1 2 4
3 4 8
5 6 12

Basics Matrices

Special Matrices
null matrix: M = [];
nxm matrix of zeros:
nxm matrix of ones:
nxn identity matrix:

M = zeros(n,m);
M = ones(n,m);
M = eye(n);

--Try these Matrices


[eye(2);zeros(2)],[eye(2);zeros(3)], [eye(2),ones(2,3)]
BEIT, 6th Semester

Matrix Operations

Matrix operations:
A+B is valid if A and B are of same size
A*B is valid if As number of columns equals
Bs number of rows.
A/B is valid and equals A.B-l for same size
square matrices A & B.

Element by element operations:


.* , ./ , .^ etc
--a = [1 2 3], b = [2 2 4],
=>do a.*b and a*b
BEIT, 6th Semester

Order of Operations

Parentheses
Exponentiation
Multiplication and division have equal
precedence
Addition and subtraction have equal
precedence
Evaluation occurs from left to right
When in doubt, use parentheses

MATLAB will help match parentheses for you

Logical Operators

Operators (Element by
Element)
.*
element-by-element multiplication
./ element-by-element division
.^ element-by-element power

The use of . Element


A = [1 2 3; 5 1 4; 3 2
Operation
1]
A=

1
5
3

2
1
2

x = A(1,:)
x=

3
4
-1

y = A(3 ,:)
3

y=

3 4 -1

b = x .* y

c=x./y

d = x .^2

b=

c=
0.33
-3

d=

-3

3 8

0.5

K= x^2
Erorr:
??? Error using ==> mpower Matrix must be square.
B=x*y
Erorr:
??? Error using ==> mtimes Inner matrix dimensions must agree.

Waveform
representation

BEIT, 6th Semester

2D Plotting
creates linear continuous plots of
vectors and matrices;
plot(t,y): plots the vector t on the x-axis
versus vector y on the y-axis.
To label your axes and give the plot a title,
type
xlabel('time (sec)')
ylabel('step response')
title('My Plot')
Change scaling of the axes by using the
axis command after the plotting
command:axis([xmin xmax ymin ymax]);

plot:

BEIT, 6th Semester

2D Plotting

stem(k,y): for discrete-time signals this


command is used.

To plot more than one graph on the screen,


subplot(m,n,p): breaks the Figure window
into an m-by-n matrix of small axes,
selects the p-th sub-window for the current
plot

grid : shows the underlying grid of axes


BEIT, 6th Semester

Example: Draw sine wave

t=-2*pi:0.1:2*pi;
y=1.5*sin(t);
plot(t,y);
xlabel('------> time')
ylabel('------> sin(t)')

BEIT, 6th Semester

Matlab Plot

BEIT, 6th Semester

Example: Discrete time


signal

t=-2*pi:0.5:2*pi;
y=1.5*sin(t);
stem(t,y);
xlabel('------> time')
ylabel('------> sin(t)')

BEIT, 6th Semester

Matlab Plot

BEIT, 6th Semester

Basic Task: Plot the function


sin(x) between 0x4

Create an x-array of 100 samples between 0


and 4.
>>x=linspace(0,4*pi,100);

Calculate sin(.) of the x-array


1
0.8
0.6

>>y=sin(x);

Plot the y-array

0.4
0.2
0
-0.2
-0.4

>>plot(y)

-0.6
-0.8
-1

10

20

30

40

50

60

70

80

90

100

Plot the function e-x/3sin(x)


between 0x4

Create an x-array of 100 samples between


0 and 4.
>>x=linspace(0,4*pi,100);

Calculate sin(.) of the x-array


>>y=sin(x);

Calculate e-x/3 of the x-array


>>y1=exp(-x/3);

Multiply the arrays y and y1


>>y2=y*y1;

Plot the function e-x/3sin(x)


between 0x4

Multiply the arrays y and y1 correctly


>>y2=y.*y1;

Plot the y2-array


>>plot(y2)

0.7
0.6
0.5
0.4
0.3
0.2
0.1
0
-0.1
-0.2
-0.3

10

20

30

40

50

60

70

80

90

100

Display Facilities

0.7
0.6

plot(.)

0.5
0.4
0.3

Example:
>>x=linspace(0,4*pi,100);
>>y=sin(x);
>>plot(y)
>>plot(x,y)

stem(.)

0.2
0.1
0
-0.1
-0.2
-0.3

10

20

30

40

50

60

70

80

90

100

10

20

30

40

50

60

70

80

90

100

0.7
0.6
0.5
0.4
0.3

Example:
>>stem(y)
>>stem(x,y)

0.2
0.1
0
-0.1
-0.2
-0.3

Display Facilities

title(.)
>>title(This is the sinus function)

xlabel(.)

This is the sinus function

1
0.8
0.6
0.4

ylabel(.)

0.2
sin(x)

>>xlabel(x (secs))

0
-0.2
-0.4
-0.6

>>ylabel(sin(x))

-0.8
-1

10

20

30

40

50
60
x (secs)

70

80

90

100

Flow Control
if
for
while
break
.

Control Structures
Some Dummy Examples
If

Statement Syntax
if ((a>3) & (b==5))

if (Condition_1)
Matlab Commands
elseif (Condition_2)
Matlab Commands
elseif (Condition_3)
Matlab Commands
else
Matlab Commands
end

Some Matlab Commands;


end
if (a<3)
Some Matlab Commands;
elseif (b~=5)
Some Matlab Commands;
end
if (a<3)
Some Matlab Commands;
else
Some Matlab Commands;
end

Control Structures
For

loop syntax

for i=Index_Array
Matlab Commands
end

Some Dummy Examples


for i=1:100
Some Matlab Commands;
end
for j=1:3:200
Some Matlab Commands;
end
for m=13:-0.2:-21
Some Matlab Commands;
end
for k=[0.1 0.3 -13 12 7 -9.3]
Some Matlab Commands;
end

Control Structures

While Loop Syntax

while (condition)
Matlab Commands
end

Dummy Example
while ((a>3) & (b==5))
Some Matlab Commands;
end

Use of M-File
Click to
create a new
M-File

Extension .m
A text file containing script or function or
program to run

Use of M-File

Save file as Denem430.m

If you include ; at the


end of each statement,
result will not be shown
immediately

Example: Draw unit step and


delayed unit step functions

n=input('enter value of n')


t=0:1:n-1;
y1=ones(1,n); %unit step
y2=[zeros(1,4) ones(1,n-4)]; %delayed unit step
subplot(2,1,1);
stem(t,y1,'filled');ylabel('amplitude');
xlabel('n----->');ylabel('amplitude');
subplot(2,1,2);
stem(t,y2,'filled');
xlabel('n----->');ylabel('amplitude');
BEIT, 6th Semester

Matlab Plot

BEIT, 6th Semester

Loops, flows:
for m=1:10:100
num = 1/(m + 1)
end

%i is incremented by 10 from 1 to 100


I = 6; j = 21
if I > 5
k = I;
elseif (i>1) & (j == 20)
k = 5*I + j
else
k = 1;
end
%if statement
BEIT, 6th Semester

Practice
1>Draw a straight line satisfying the equation: y = 3*x + 10
2> Create matrices with zeros, eye and ones
3>Draw a circle with radius unity. (use cos for x axis, sin for y
axis)
4>Draw a cosine wave with frequency 10kHz. Use both plot and
stem functions to see the difference.
5>Multiply two matrices of sizes 3x3.
6>Plot the parametric curve x(t) = t, y(t) = exp(-t/2) for 0<t<pi/2
using ezplot
7>Plot a cardioid r() = 1 + cos() for 0< <pi/2
BEIT, 6th Semester

Graphics - Overlay Plots


Use hold on for overlaying graphs
So the following:
Gives:
>> hold on;
>> cub=x.^3;
>> pl2=plot(x, cub,b-o');

Graphics - Annotation
Use title, xlabel, ylabel and legend for
annotation

>> title('Demo plot');


>> xlabel('X Axis');
>> ylabel('Y Axis');
>> legend([pl1, pl2], 'x^2', 'x^3');

Graphics-Stem()
stem()is to plot discrete sequence data
The usage of stem() is very similar to plot()

cos(n/4)

>>
>>
>>
>>

n=-10:10;
f=stem(n,cos(n*pi/4))
title('cos(n\pi/4)')
xlabel('n')

0.5

-0.5

-1
-10

-5

0
n

10

subplots

Use subplots to divide a plotting window


into several panes.
Cosine

>>
>>
>>
>>
>>
>>
>>
>>
>>
>>

x=0:0.1:10;
f=figure;
f1=subplot(1,2,1);
plot(x,cos(x),'r');
grid on;
title('Cosine')
f2=subplot(1,2,2);
plot(x,sin(x),'d');
grid on;
title('Sine');

0.8

0.8

0.6

0.6

0.4

0.4

0.2

0.2

-0.2

-0.2

-0.4

-0.4

-0.6

-0.6

-0.8

-0.8

-1

Sine

10

-1

10

Save plots

>>
>>
>>
>>
>>
>>
>>

Use saveas(h,'filename.ext') to save


a figure to a file.

f=figure;
x=-5:0.1:5;
h=plot(x,cos(2*x+pi/3));
title('Figure 1');
xlabel('x');
saveas(h,'figure1.fig')
saveas(h,'figure1.eps')

Useful extension types:


bmp: Windows bitmap
emf: Enhanced metafile
eps: EPS Level 1
fig: MATLAB figure
jpg: JPEG image
m: MATLAB M-file
tif: TIFF image, compressed

Practice Problems

Plot the following signals in linear scale

x(t ) sin(3t )

5 t 5

y (t ) e 2t 3
0t 5
Plot the following signals, use log scale for y-axis

Plot thex(real
t ) part
e t 2 (2and
t 1)imaginary
0 t 10part of the following signal

.5 t j ( t / 3 )
(t ) e 0in
t 10 plot its phase and magnitude
For thexsignal
previous 0question,

Other MATLAB symbols


>>
...
,
%
line
;
:

prompt
continue statement on next line
separate statements and data
start comment which ends at end of
(1) suppress output
(2) used as a row separator in a matrix
specify range

MATLAB Help

Ways to get help in


MATLAB

help function name


Provides basic
text output

Type helpwin on
command line
Look under the help menu
on the desktop

You might also like