0% found this document useful (0 votes)
96 views19 pages

Introduction To MATLAB and Basic Signals: Definition of Variables

This document provides an introduction to MATLAB and basic signals. It discusses using MATLAB for digital signal processing, which involves matrix manipulations and calculations. Various MATLAB functions and operations are defined for working with variables, vectors, matrices, and signals. Key features of MATLAB include predefined functions, operators, and the ability to perform element-by-element operations on matrices and vectors.

Uploaded by

nouman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
96 views19 pages

Introduction To MATLAB and Basic Signals: Definition of Variables

This document provides an introduction to MATLAB and basic signals. It discusses using MATLAB for digital signal processing, which involves matrix manipulations and calculations. Various MATLAB functions and operations are defined for working with variables, vectors, matrices, and signals. Key features of MATLAB include predefined functions, operators, and the ability to perform element-by-element operations on matrices and vectors.

Uploaded by

nouman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Signals and Systems Lab DEE, FURC

Introduction to MATLAB and Basic Signals


Over the past few decades, the unbelievable progress in the field of digital signal processing has
altered t e hem ntireo t w eaning ‘ b f t he t ord u impossible’,
a d t u y h
doable. With an ever-increasing set of applications, signal processing has crept into almost every
sphere of science, and today, we see the techniques and tools developed by DSP scientists an
engineers b u eing
f a b tilized u ora i etter o t nderstanding
u a h t nd nv
life. This field of knowledge has helped us to stretch our limits --- the very limits of thinking and
i m a gi n at i on ; t h e m os t ch e ri s h -a bl e ou tc o me of a l l t he kn ow l e dg e . A s ou r fi rs t c ou rs e on D
we’ll try to familiarize ourselves with the concepts and theory of DSP, to have a look at and use
the tools to solve the practical problems, and to have a flavor of the problems and the challenges
faced by man in the past, as well as today.

MATLAB is the most popular tool used for Digital Signal Processing. It provides on
strongest environments for study and simulation of the real-world problems and their solutions,
especially in the field of engineering. For Signal Processing, it has a very comprehensi
easy-to-use t w oolbox
l o D f ith i ots f M SP w unctions
t a o S mplemented.
we can create much more complex situations very easily, and solve them.

MATLAB (abbreviation for Matrix Laboratory) is a matrix based system whi


Engineering a M nd c athematical
I i c alculations.
v p t ntegrates
to use environment where problems and solutions are expressed i
notation. I i a kindt o ls f anguage
w hichi d s t esigned
d m m o o A vatrix u anipulations.
in MATLAB are matrices. It means that MATLAB containsonly one data type and a matrix or a
rectangular array of numbers. MATLAB contains a large set of routines to ob
outputs. There are many predefined functions in MATLAB which are called by the user to solve
many different types of problems.
Typical uses include:

 Math and computation


 Algorithm development
 Data Acquisition
 Modeling, Simulation, and prototyping
 Data analysis, exploration, and visualization
 Scientific and engineering graphics
 Application development, including graphical user interface building

DEFINITION OF VARIABLES

Variables are assigned numerical values by typing the expression directly, for example, typing

1
Signals and Systems Lab DEE, FURC

a = 1+2;

yields: a = 3;

The a nswer
w n b d ill wot a se isplayed
i p a t e ohen
a e emicolon
f e s ut
type

a = 1+2;

MATLAB utilizes the following arithmetic operators:

 +  addition
 -  subtraction
 *  multiplication
 /  division
 ^  power operator
 '  transpose

A va r i ab l e c an b e a s s i g ne d us i n g a f or mu l a t ha t u t i li z e s t h es e op e ra t or s a n d ei t h er n um b er
previously defined variables. For example, since a was defined
expression is valid

b = 2*a;

To determine the value of a previously defined quantity, type the quantity by itself:

yields: b = 6;

If your expression does not fit on one line, use an ellipsis (three or more periods at the end of the
line) and continue on the next line.

c = 1+2+3+...
5+6+7;
 
There a s re p everal v redefined
w c b u a ariables
a t i t s hich
m a an
u e sed
defined variables:

2
Signals and Systems Lab DEE, FURC

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

For example:

y= 2*(1+4*j);

yields: y = 2.0000 + 8.0000i;

PRE DEFINED FUNCTIONS IN MATLAB

There are also a number of predefined functions that can be used when defining a variable. Some
common functions that are used in this text are:

 m a g n i t u d e o f a n u m b e r ( a b s o l u t e
abs
value for real numbers)
 A n g l e o f a c o m p l e x n u m b e r , i n
angle
radians
 cosine function, assumes argument is
cos
in radians
 sine function, assumes argument is in
sin
radians
exp  exponential function
 
For example, with y defined as above,

c = abs(y);

yields: c = 8.2462;

c = angle(y);

yields: c = 1.3258;

With a=3 as defined previously,

c = cos(a);

yields: c = -0.9900;

3
Signals and Systems Lab DEE, FURC

c = exp(a);

yields: c = 20.0855;

Note that exp can be used on complex numbers. For example, with y = 2+8i as defined above,

c = exp(y);

yields: c = -1.0751 + 7.3104i;

which can be verified by using Euler's formula:

c = exp(2)*cos(8) + j*(exp)2*sin(8);

DEFINITION OF MATRICES

M A T L A B i s b a s e d o n m a t r i x a n d v e c t o r a l
11 m a t r i c e s . T h e r e f o r e , v e c t o r a n d m a t r i x o p e r a t i o n s a r e a s s i m p l e a s
operations.
V e c tc oa r n s b e d e f i n e d i n t w o w a y s . T h e f i r s t
elements

v=[1 3 5 7];
creates a 14 v ectorw e ith 1 3 5lements
a 7 N t c, , c nd
h b . u otei p hat omma
o f s p a c e s t o s e p a r a t e t h e e l e m e n t s . A d d i
vector:

v(5)=8;

yields the vector v=[1 3 5 7 8]. Previously defined vectors can be used to define a new vector.

For example, with v

a=[9 10];
b=[v a];

creates the vector

b=[1 3 5 7 8 9 10].

The second method is used for creating vectors with equally spaced elements:

4
Signals and Systems Lab DEE, FURC

t=0: 0.1:10;

creates a 1x101 vector with the elements 0, .1, .2, .3,...,10. Note that the middle number defines
the increment. If only two numbers are given, then the increment
1

k=0:10;

creates a 111 vector with the elements 0, 1, 2, ..., 10.

Matrices are defined by entering the elements row by row:

M=[1 2 4; 3 6 8];

creates the matrix.

There are a number of special matrices that can be defined:


null matrix:

M=[ ];

nm matrix of zeros:

M=zeros(n,m);

nm matrix of ones:

M=ones(n,m);

nn identity matrix:

M=eye(n);

A particular element of a matrix can be assigned:

M(1,2)=5; places the number 5 in the first row, second column.


Operations and functions that were defined for scalars in the previous section can also be used on
vectors and matrices. For example,

5
Signals and Systems Lab DEE, FURC

a=[1 2 3];
b=[3 4 5];
c=a+b;
yields: c=[5 7 9];

Type equation here .

Functions are applied element by element. For example,

t=0:10;
x=cos(2*t);

c r e a t e s ax wv ie t c ht o e r l e m e n ct so s e( qf2 uot ar ) l t t =o 0 , 1 , 2 , . . .

Operations that need to be performed element-by-element can be accomplished by preceding the


o p e r a t i o n ."b .y Fa o r" e x a m p l e , t o o b t a i n a v e c t o r x t h a t c o n t
x(t) = tcos(t a )t s p e c i f i c p o i n t s i n t i m e , y o u c a n n o t s i m p l y m u l t i p l y t h e v e c t o r t w i t h
vector cos(t).
Instead you multiply their elements together:

t=0:10;
x = t .*cos(t);

M-FILES

M-files are macros of MATLAB commands that are stored as ordinary t


extension "m", that is ‘filename.m’. An M-file can be either a function with input and
variables or a list of commands. MATLAB requires that the M-file must be stored either in the
working directory or in a directory that is specified in the MATLAB path list. Fo
consider using MATLAB on a PC with a user-defined M-file stored in a directory called
" \MATLAB\MFILES".T t a t M hen
e c o t ccess w d hat b -file,
t ither
cd\matlab\mfiles from within the MATLAB command window or by adding the directory to the
path. Permanent addition to the path is accomplished by editing the \MATLAB\matlabrc.m file,
w h i l e t e m p o r a r y m o d i f i c a t i o n
path(path,'\matlab\mfiles') f w M O rom
t c e ithinb a ATLAB.
t t p r, hi
browser. As example of an M-file that defines a function, create a file in your working directory
n a m e d y p l u s x . m

function yplusx(y,x)
z=y+x

6
Signals and Systems Lab DEE, FURC

The following commands typed from within MATLAB demon


u s

x=2
y=3
z = yplusx(y,x)

All variables used in a MA TLAB function are local to that function only. V ariables which a
used in a script m-file which is not a function are all global variables.

MATLAB M-files are most efficient when written in a way that utiliz
o p e r a t i o n s . L o o p s a n d i f s t a t e
sparingly s t aincec hey i re omputationally
A e o t u o t cnefficient.f i n

for k=1:10;
x(k) = cos(k);
end

This creates a 110 vector x containing the cosine of the positive integers from 1 to 10. This
operation is performed more efficiently with the commands:

k= 1:10;
x=cos(k);

which utilizes a function of a vector instead of a for loop. An if statement can be used to define
conditional statements; e.g.

if(a<=2);
b=1;
elseif(a>=4)
b=2;
else
b=3;

T h e a l l o w a b l e c o m p a r i s o > n,= s< ,=b <,e >t , w= e,= e an n ~ ed.=x p r e s

S u p p o s e t h a t y o u w a n t t o r u n a n M - f i l e w
T. T h e f o l l o w i n g c o m m a n d l i n e w i t h i n t h e M -
T = i n p u t ( ' I n

7
Signals and Systems Lab DEE, FURC

Whatever comment is between the quotation marks is displayed to the screen when the M-file is
running, and the user must enter an appropriate value.

PLOTTING GRAPHS

Commands: plot, xlabel, ylabel, title, grid, axis, axes, stem, subplot, zoom, hold

T h e c o m m a n d m o s t o f t e n u s e d f o r p lpolt toit,n gw hi si c h c r e a t e s l i n e a r p l o t s o f v e c t o r s a n d
m a t r i c e sp;l o t ( t , y p)l o t s t h e v e c tto ro n t h e x - a x i s v e r s u s v eyc ot onr t h e y - a x i s . T h e r e a r e
o p t i o n s o n t h e l i n e t y p e a n d t h e c o l o r o f t
plot(t,y,'option'). T hel inetype
o a ' s ptions l ( re ' d-' olid
l ' d ined default),
line, ':' dotted line. The points in y can be left unconnected and delineated
s y m b o l s+: . * o .x T h e f o l l o w i n g c o l o r s a r e a v a i l a b rl e, ogp,t i obn,s : k , y , e tmc .
For e xample,
plot(t,y,'--') u sesa d l ashed
plot(t,y,'*') ine, u ses* a ta t ll p he d oints efin
in t and y without connecting the points, and plot(t,y,'g') uses a solid green line. The options
c a n a l s o b e u s e d t o g e t ph le or t, ( fto,r y p,e l'xoga t m :s 'p a)l e d, o t t e d g r e e n
T o p l o t t w o o r m o r e g r a p h s o n t h e s a m e
plot(t1,y1,t2,y2), which plots y1 versus t1 and y2 versus t2.

To label your axes and give the plot a title, type

xlabel (‘time (sec)’)


ylabel(‘step response’)
title(‘my plot’)
Finally, add a grid to your plot to make it easier to read. Type grid on

The problem that you will encounter most often when plotting functions is that MATLAB will
scale t a he i a wxes t i nd ay
t y hat
w t s t ifferent
a Y c ehan o ou t ant hem
auto scaling of the axes by using the axis command after the plotting command

axis([xmin xmax ymin ymax]);


where xmin, xmax, ymin, and ymax are numbers corresponding to the limits you desire for the
axes. To return to the automatic scaling, simply type axis.

For discrete-time signals, use the command stem which plots each point with a small open circle
and a straight line. To plot y[k] versus k, type stem(k,y)

You can use stem(k,y,'filled') to get circles that are filled in.

To plot more than one graph on the screen, use the command subplot(mnp) which partitions the
screen into an mn grid where p determines the position of the particular graph counting the

8
Signals and Systems Lab DEE, FURC

upper left corner as p=1. For example,

s u
subplot(212),semilogx(w,phase);

plots the bode plot with the log-magnitude plot on top and the phase plot below. Titles and labels
can b i e nserted
i a mmediately
t a semilogx fter
c ommando
he p ppropriate
c r lot
T r ommand.
to a full screen plot, type subplot(111).

Addition, Subtraction, Multiplication and Division of integers

Write t f he collowing
i c w ode o Mn ommand
E t w yindow
w f
a line of code, press ENTER.

» 3+5
ans =
8

» x=3
x=
3

» y=5
y=
5

» x+y
ans =
8

» z=x+y
z=
8

What y h oul ave


f t earned
a c W romw w he3 Mbove w ode.a t hen
t w o n u m b e r s f o r y o u a n d s t o r e t h e
a n .s W h e n y o u w xr =i t3ea n dy = 5, M A T L A B s t o r e s t h e i n t e g3e ar nvda5 l iune s
v a r i a bx la ens dy r e s p e c t i v e l y . A d d i n g t h e s e 2 v a r i a b l e s
x+y, the resultant value8 is assigned/stored in variableans. If we want the sum of two
variables to be stored into a third variable such z, aswe write the statementz=x+y. this

9
Signals and Systems Lab DEE, FURC

means t f hata irst


o x and ddition
y i sp erformed
a f t t r nd i s han i v he esult
z, not the by default variable ans.

Use
- for Subtraction
* for Multiplication
/ for Division
^ for Power
P r a c t i c e s o m e s u b t r a c t i o n , m u l t i p l i c a t i o n a n d d i v i s i
parameters.

AND, OR, NOT, XOR

Try some of the Logical operations as demonstrated below.

» c=and(1,1)
c=
1

» c=and(1,0)
c=
0

» x=1
x=
1

» y=1
y=
1

» c=or(x,y)
c=
1

» y=0
y=
0

» c=xor(x,y)
c=

10
Signals and Systems Lab DEE, FURC

» b=not(1)
b=
0

a n d ( x ,, yo )r ( x ,, yx)o r ( x , ay n) dn o t ( xa)r e b u i l t i n f u n c t i o n s i n M A T L A B . T h e i
p a r a m e t e( rx s, y c) a n b e e i t h e r g i v e n d i roerc( t1l ,y0o )ra si n d i r e c t l y i n t h e f o r m o f
v a r i a b l e s b y f i r s t d e c l a r i n g v axr =
i a1,byl e=s0 a n d t h a no r ( x , y. )B o t h f o r m s w i l l g i v e
same result.
Home Exercise 01:

Implement the following using and(x,y), or(x,y), not(x).

y=not ( (1and1) or (1or0) or (not (0)) )

Home Exercise 02:

The following is an example to calculate powers


» x=3
x=
3

» y=x^2
y=
9

Implement the following equation in MATLAB and find the resultant

x=4; y=5; z=3;


result=(x+3)^2*4/(3*(z+y));

MATRICES

If we want to construct a row matrix with 1*6 dimensions type the following
» m=0:1:5
m=
0 1 2 3 4 5

To convert the matrix into a column matrix with 6*1 dimensions type the following
» m=transpose (m)

11
Signals and Systems Lab DEE, FURC

m=
0
1
2
3
4
5
A different method to construct a matrix is by giving values to each and every element
of a matrix such as

» a(1,1)=3;
» a(1,2)=5;
» a(1,3)=7;
» a(1,4)=9;
»a
a=
3 5 7 9

T h e g e n e r a l f o r m aat( xi s, y w
) h i c h m e a nms a t r i x w
a i t h t h e e l e m e n tx irno wa n d y
column.

Similarly for a row matrix

» b(1,1)=3;
» b(2,1)=5;
» b(3,1)=7;
» b(4,1)=9;
»b
b=
3
5
7
9

For constructing a matrix with m*n dimension

» c(1,1)=1;
» c(1,2)=3;
» c(2,1)=3;
» c(2,2)=5;
»c

12
Signals and Systems Lab DEE, FURC

c=
1 3
3 5

Type the following and see what happens

» d(3,2)=-5

By the above statement we have assigned a value to only one element of the matrix, and
the remaining elements of the matrix are assigned value 0.

Addition, Subtraction, Multiplication of Matrices

» clear
» x=1:1:3;
» y=1:1:3;
» m(x,y)=1;
»m
m=
1 1 1
1 1 1
1 1 1

» n(x,y)=2;
»n
n=
2 2 2
2 2 2
2 2 2

» a=m+n
a=
3 3 3
3 3 3
3 3 3

» b=m-n
b=
-1 -1 -1
-1 -1 -1
-1 -1 -1

13
Signals and Systems Lab DEE, FURC

» c=a*n
c=
18 18 18
18 18 18
18 18 18

For finding determinant of a matrix use

» det(a)
ans =
0

Creating a Matrix with the help of Loops

» z=1:1:9
z=
1 2 3 4 5 6 7 8 9

» n=1
n=
1

» for i=1:3,
for j=1:3,
d(i,j)=z(1,n);
n=n+1;
end
end
»d
d=
1 2 3
4 5 6
7 8 9

Home Exercise 03

14
Signals and Systems Lab DEE, FURC

With t h heo o elpLoops afnda row


nly o rc olumn
m [ 2 3atrix
4 5 6 7 8 91 d t
following matrix

1 2 3 0 0 0 9 8 7
4 5 6 0 0 0 6 5 4
7 8 9 0 0 0 3 2 1

Home Exercise 04

Another way of designing a row matrix is

» clear
» x=[1 2 3 4 5 6 7 8 9]
x=
1 2 3 4 5 6 7 8 9

Modify the matrixx in such a way that between every 2 elements of x a new element is
inserted and which is the average of the two adjacent elements.
Size of Matrix

Size of a matrix can be calculate by using function ‘size ‘.

X= [1 2 3 ;12 3 5];
size(X)

length of array:

length of an array can be found using function length.

X=1:10;
length(X)

Find:
This function can be used to find index of any particular value.

Say given array is


X= [ 1 2 3 4];
say I want to find indices of all values that are greater than 2
find(X>2)

15
Signals and Systems Lab DEE, FURC

There are several predefined variables which can be used at any time, in the same manner as
user- defined variables:
i sqrt(-1)
j sqrt(-1)
pi 3.1416...

For example,
y= 2*(1+4*j)
yields: y= 2.0000 + 8.0000i

There are also a number of predefined functions that can be used when defining a variable.
Some common functions that are used in this text are:
abs magnitude of a number (absolute value for real numbers)
angle angle of a complex number, in radians
cos cosine function, assumes argument is in radians
sin sine function, assumes argument is in radians
exp exponential function

For example, with y defined as above,


c = abs(y)
yields: c = 8.2462
c = angle(y)
yields: c = 1.3258
With a=3 as defined previously,
c = cos(a)
yields: c = -0.9900
c = exp(a)
yields: c = 20.0855

16
Signals and Systems Lab DEE, FURC

17
Signals and Systems Lab DEE, FURC

Commands covered:
plot
xlabel
ylabel
title
grid
axis
stem
subplot
The command most often used for plotting is ‘plot’, which creates linear plots of vectors and
matrices; plot(t,y) plots the vector t on the x-axis versus vector y on the y-axis. There are
options on the line type and the color of the plot which are obtained using plot(t,y,'option').
The linetype options are '-' solid line (default), '--' dashed line, '-.' dot dash line, ':' dotted line.
The points in y can be left unconnected and delineated by a variety of symbols: ・+ . * o
x・. The following colors are available options:
r red
b blue
g green
w white
k black
For example, plot(t,y,'--') uses a dashed line, plot(t,y,'*') uses * at all the points defined in t
and y without connecting the points, and plot(t,y,'g') uses a solid green line. The options can
also be used together, for example, plot(t,y,'g:') plots a dotted green line.
To plot two or more graphs on the same set of axes, use the command plot(t1,y1,t2,y2),
which plots y1 versus t1 and y2 versus t2.
To label your axes and give the plot a title, type;
xlabel('time (sec)')
ylabel('step response')
title('My Plot')

18
Signals and Systems Lab DEE, FURC

Finally, add a grid to your plot to make it easier to read. Type ‘grid’.
The problem that you will encounter most often when plotting functions is that MATLAB
will scale the axes in a way that is different than you want them to appear. You can easily
override the auto scaling of the axes by using the axis command after the plotting command:
axis([xmin xmax ymin ymax]);
where xmin, xmax, ymin, and ymax are numbers corresponding to the limits you desire for
the axes. To return to the automatic scaling, simply type ‘axis’.
For discrete-time signals, use the command ‘stem’ which plots each point with a small open
circle and a straight line. To plot y[k] versus k, type
stem(k,y)
You can use stem(k,y,'filled') to get circles that are filled in.
To plot more than one graph on the screen, use the command subplot(mnp) which partitions
the screen into an mxn grid where p determines the position of the particular graph counting
the upper left corner as p=1. For example,
subplot(211),
subplot(212),

This has 2 rows, one column, and one plot in each row.

Loading and Saving Data

When using MATLAB, you may wish to leave the program but save the vectors and matrices
you have defined. To save the file to the working directory, type save filename where
"filename" is a name of your choice. To retrieve the data later, type load filename. Or simply
save and open the file from the menue.

19

You might also like