Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Communications Lab._Lec. 1_Introduction to MATLAB and Signals in MATLAB

Uploaded by

Zaid Mustafa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Communications Lab._Lec. 1_Introduction to MATLAB and Signals in MATLAB

Uploaded by

Zaid Mustafa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Introduction to MATLAB and Signals in MATLAB

Objectives
To familiarize the students with MATLAB and the basic concept of signals in the MATLAB. Following are the
main features of the experiment.

ü Introduction to MATLAB
ü Plotting of Continuous and Discrete time signals on MATLAB.

Part 1 –Introduction to MATLAB


What is MATLAB?
MATLAB is a high-level technical computing language equipped with a user-friendly interface. Its name stems
from the words MATrix and LABoratory as it is based on the use of matrices. MATLAB is an extremely
powerful tool useful for scientists and engineers from various disciplines. For example, MATLAB can be used
in a wide range of applications, such as telecommunications, signal and image processing, control,
mathematics, financial modelling, bioengineering, aeronautics, and many more.

M-Files
In order to write many commands that are executed all together, the program must be written in a
text editor. In this editor, one can type all the needed commands to form a program, save the
program, and execute it any time he or she wants. The text files are called M-files due to their suffice
*.m.

There are two categories of M-files: the Scripts and the Functions.

Scripts
Sripts are the M-files with MATLAB commands. Their name must have a .m suffix. Scripts are suitable for
solving the problems that require many commands. The advantage of the scripts is that they are
implemented very easily.

Lab Task
Write a script file and execute.

Solution
% Program to understand the use of script file
% Muhammad Usman Iqbal
% EEE223 Signals and Systems
clc
close all
clear all
% All commands that are
% needed are typed in the
% .m File. Everything written
% at the right of symbol %
% is a comment and is not
% taken into account
t=-5:0.1:5;
f=t.*cos(2*pi*t);
plot(t,f);
Functions
Function are also M-files, That is, are files with extension .m and must be saved in the current
Directory of MATLAB. The difference between functions and scripts is that a function accepts one or
more input arguments and returns one or more output arguments. To declare that an M-file is a
function the first line of the m file must contain the syntax definition. More specifically, the first line
of the M-file must be of the form function[y1,y2,y3,…yn]=name{x1,x2,x3… xm}. The variable
y1,y2,…yn are the outputs of the function while x1,x2,…xm are the input arguments. In case there is
only one output, the square brackets are not necessary. The “name” specifies the name of the
function. In order to execute a function, first the M-File is saved in Current Directory.

Lab Task
Write a function file and execute. Function should accepts as input two matrices and returns their sum and
product.

Solution
function [sm,pro]=oper(A,B)

sm=A+B;
pro=A*B;

clc
close all
clear all

% to test the function operation


% Enter the matric A
A= [ 2 3; 4 5]
% Enter Matrix B
B= [4 5; 5 6]
[sm,pro]=oper(A,B)
A =
2 3
4 5
B =
4 5
5 6
sm =
6 8
9 11
pro =
23 28
41 50

Useful Commands
Here we will learn and practice useful (when workig with vectors and matries) commands. As already
discussed, the command sum returns the sum of the elements of a vector. The command cumsum returns a
vector whose elements are the comulative sum of the previous elements, the command prod is the product
of the vector elements, while the command diff returns a vector in which each element is given by its
subtraction with the previous element. The command max and min return the largest and smallest
elements of the vector,respectively, as well as their index. The command sort sorts the vector elements in
ascending(by default) or descending order. The command mean computes the mean value, while the
command median returns the median value. All these commands are suitable also for matrices by slightly
changing their syntax.

Commands Results/Comments
a = [4 2 7 0 6] a = 4 2 7 0 6
%Definition of vector .
s = sum(a) s = 19
%Sum the elements of .
c = 4 6 13 13 19
c = cumsum(a) %Cumilative sum.the result is obtained as[4,4+2,4+2+7,
4+2+7+0, 4+2+7+0+6]
p = 0
p = prod(a)
%Product of all elements.
d = -2 5 -7 6
d = diff(a) %Difference between two consecutive elements i.e.,
d(1)=! (2)-! (1),etc.
[m,i] = max(a) m = 7
i = 4
%The largest value is assigned to variable ",and its
index is aasigned to variable #.

[m,i] = min(a) m = 0
i = 3
%The smaller value is assigned to variable ",and its
index is aasigned to variable #.

max(a) ans = 7
%If no output variable is specified,only the largest value
mean(a) is returned.

ans = 3.8000
median(a)
%Mean value of the elements.

sort(a) ans = 4
%Median value of the vector.

ans = 0 2 4 6 7
sort(a,’descend’) %Sorting in ascending order.

ans = 7 6 4 2 0
%Sorting in descending order.

Special Forms of Matrices


The command ones(M,N) creates a matrix of size MxN with ones. Typing ones(M) returns a square
matrix with ones. Similarly, the command zeros(M,N) creates a matrix of size MxN with zeros. The
command rand(M,N) returns an MxN matrix with random elements. The command eye(M,N) defines
an MxN matrix with ones in the main diagonal zeros everywhere. The command magic(M) creates a
square matrix with the property that the sum of each row or column is equal.

Commands Results/Comments
ones(2,3) ans = 1 1 1
1 1 1
%Matrix of size 2x3 with ones.

zeros(1,4) ans = 0 0 0 0
%Matrix of size 1x4(or vector of length)with zeros.

ans = 0.8600 0.9000 0.4600


rand(3) 0.6000 0.1000 -0.3000
0.4540 0.6023 0.2700
%Matrix of size 3x3 with random elements. If there is one
input argument to the command, the obtained matrix is
square.

eye(4,2) ans = 1 0
0 1
0 0
0 0
%Magic of size 4x2 with ones in the main diagonal and
zeros elsewhere.

Ans = 1 0 0
eye(3) 0 1 0
0 0 1
%The identity matrix 1 of size 3x3.

A = 8 1 6
A = magic(3) 3 5 7
4 9 2
%Magic matrix

Symbolic Variables

In MATLAB, a variable type is the symbolic variable (or object). A symbolic variable is defined by the
command sym and syms. The use of symbolic variables allows the computation of limits, integrals,
derivatives etc.
Part II- Plotting Signals in MATLAB
MATLAB is a very reliable and power full tool for plotting. A graph is constructed as a set of points
in two or three dimensions. These points are typically connected with a solid line. Commonly a
graph of a function is required. However in MATLAB a plot is done using the vectors and matrices
not functions.

Plotting in Two Dimensions


Suppose that we want to plot a function $(%), where %!is an independent variable. The procedure to plot
$(%) is as follows:

1. Vector x is created. Such as ! " ! #, where a and ab are scalars.


2. The function $(") will be plotted over the interval [ , #].
3. Create the vector $, which is of the same length as ". The two vectors have an equal number of
elements.
4. The value of each element of $ is the value of $(") calculated for each value of ".
5. Finally, the function $(") is plotted by typing ‘plot(x,y)’

Lab Task
Plot the function $(") = " % ,&&&&&& ' 2 ! " ! 2

Solution

clc
close all
clear all

x=-2:2 % independent variable , length of the plot


length (x)
y=x.^2 % Function
length (y)
plot(x,y)

x=
-2 -1 0 1 2

ans =

y=
4 1 0 1 4

ans =
5
Write down modified MATLAB code to plot exactly like below

Plotting Several Function in One Figure


It is possible to plot more than one function in the name of figure by employing a different syntax of
command Plot.
Lab Task
Plot the $(") = " % cos(") , *(") = "+-/("), 01&3(") = 24 sin(") ,&&&&&5 ! " ! 26 in the same figure.

Solution

clc
clear all
close all

x = linspace(0,2*pi,100) % linespace could be used to create a vector.


x=0:pi/50:2*pi % this is same value as above. Both method are correct
y = (x.^2).*cos(x);
g = x.*cos(x);
f = (2.^x).*sin(x);
plot(x,y,x,g,x,f)

In the previous examples, the functions were plotted with predefined colors and line type (solid). It is
possible to create a graph using colors, symbols used to draw the points, and type of line that connects the
points of your choice. This is achieved by applying one more input argument to the command Plot The
new argument is a series of special character given in single quotes. The available special characters are
presented in the table below.

Symbols Color Symbol Point Type Symbol Line Type


B Blue . Point - Solid
G Green o Circle : Dotted
R Red x x-mark -. Dashdot
C Cyan + Plus _ Dashed
M Magenta * Star
Y Yellow s Square
K Black d Diamond
W White <,> Triangle
P Pentagram
h Hexagram

Formatting a Figure
The command grid on adds lines to the graph, while the command grid off removes the grid
lines. Simply typing grid is switch between the two modes. Text besides the x-axis and y-axis can
be added using the commands xlabel and ylabel, respectively. A graph title is inserted by the
Command title.

clc
clear all
close all

x = linspace(0,2*pi,150);
plot(x,cos(x),'r*',x,sin(x),'k')
grid

xlabel('Time Axis')
ylabel('Amplitude')
title('Graph of cos(x) & sin(x)')
legend('cos','sine')

Plotting in Different Figures


Up to this point, all plots were made in single figure named Figure 1. By typing at the command
prompt figure, a new figure with name Figure 2 appears without closing the old figures. The
command subplot(m,n,p) or subplot(mnp) splits the figure window into × !small
subfigures and makes the pth subfigure active.

Lab Task
Plot the functions that were plotted in last lab task in the following two ways.

1. In two different figures


2. In a figure but separately using subplot.
Plotting the Discrete Time Functions
A discrete time function is a function of the form [!], !" # $, %&'('"$")'!*+'-"+&'"-'+"* ".!+'/'(-0"In this
case the appropriate command for plotting the function is ‘stem(n,f)’

Lab Task
Plot the discrete function (!) = !" #, $%&'&# * 2 + ! + 2.

Solution

clc
clear all
close all

n = -3:3
f= n.^2
stem(n,f)

xlabel('Time Axis')
ylabel('Amplitude')
title('Graph of f(n)')

Modify the above lab task to create figure like below.


clc
clear all
close all

n = -3:3
f= n.^2
stem(n,f)

xlabel('Time Axis')
ylabel('Amplitude')
title('Graph of f(n)')

Modify the above lab task to create figure like below.


Piecewise Functions
Now we will discuss the way of defining and plotting functions with more than one part.

Lab Task
Plot the following function

1,############################ * 2 + - + 2#
(-) = . 0#################################2 < - < 5
- sin(4/-) #################5 + - + 8

Solution

clc
clear all
close all

t1=-2:.1:2;
t2=2.1:.1:4.9;
t3=5:.1:8;

f1=ones(size(t1));
f2=zeros(size(t2));
f3=t3.*sin(4*pi*t3);

t=[t1 t2 t3];
f=[f1 f2 f3];

plot(t,f)
title('Multi-part function f(t)')
xlabel( 'time')
ylabel( 'Amplitude')

You might also like