0% found this document useful (0 votes)
25 views

Comm 1 Lab 01

This document provides an introduction and overview of MATLAB for students taking a Communication Systems laboratory course. It describes MATLAB as an interactive system for scientific computation and visualization. The document then provides instructions on basic MATLAB operations like arithmetic, variables, matrices and formatting. It explains how to perform simple calculations, store values in variables, work with matrices and change output formatting. The goal is to familiarize students with basic MATLAB functions and commands before they perform exercises in the lab.

Uploaded by

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

Comm 1 Lab 01

This document provides an introduction and overview of MATLAB for students taking a Communication Systems laboratory course. It describes MATLAB as an interactive system for scientific computation and visualization. The document then provides instructions on basic MATLAB operations like arithmetic, variables, matrices and formatting. It explains how to perform simple calculations, store values in variables, work with matrices and change output formatting. The goal is to familiarize students with basic MATLAB functions and commands before they perform exercises in the lab.

Uploaded by

Dexter Pineda
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

COMMUNICATION 1: PRINCIPLES
OF COMMUNICATION SYSTEMS

Title: Study MATLAB

Name of Student: _____________________________

Course and Section: ____________________________

Date performed: ______________________________

Date Submitted: ______________________________

_________________________

Instructor

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

LABORATORY EXERCISE 1

STUDY MATLAB (EXERCISES)


1. INTRODUCTION

( a )What is MATLAB?

MATLAB is an interactive, matrix-based system for scientific and engineering numeric


computation and visualization. The word MATLAB stands for MATrix LABoratory. Each entry
is taken as a matrix in it, in particular scalar is considered as a 1 by 1 matrix. MATLAB is available
for a number of operating systems like Windows, Linux etc. MATLAB was originally written in
FORTRAN and is licensed by The Math Works, Inc,

(http:// www.mathworks.com). The version of MATLAB we use is ver 6.1. There is a relatively
inexpensive student edition available from Prentice Hall Publishers.

( b )What is the advantage of MATLAB over FORTRAN or C?

In languages like FORTRAN & C we have to declare dimensions of matrices used. But, here, by
default each entry is a matrix, therefore dimensioning of a variable is not required. We can solve
complex numerical problems in a fraction of the time required with a programming
language such as FORTRAN or C. MATLAB is also a programmable system. It contains so
many useful algorithms as built-in functions and hence programming itself is easier. The
graphic and multimedia capabilities are also commendable.

( c ) Where can we use MATLAB?

MATLAB is recognized as the interactive program for numerical linear algebra and matrix
computation. In industries, MATLAB is used for research and to solve practical
engineering and mathematical problems. Also, in automatic control theory, statistics and
digital signal processing (Time-Series Analysis) one can use MATLAB. The following tool
boxes make it useful in soft computing at various industrial and scientific areas:

(i) Neural Networks (ii) Optimization

(iii) Genetic Algorithms (iv) Wavelets

(v) Fuzzy Logic (vi) Control systems

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

(vi) Signal Processing

2. MATLAB GETTING STARTED

By clicking the MATLAB shortcut icon on the desktop of your computer (or selecting from the

program menu) you can access MATLAB. This results in getting MATLAB command window with
its prompt:

>>

with a blinking cursor appearing right of the prompt, telling you that MATLAB is waiting to
perform a mathematical operation you would like to give.

Simple Math Calculations

( i ) If you want to add two numbers say 7 & 12, type as follows

>> 7+12

and press the ENTER or return key, you see the following output:

ans =

19

Here, ans stands for the answer of computation. Similarly, the following gives product
and difference of these numbers,

>> 7*12 <ENTER>

ans =

84

>> 12-7 <ENTER>

ans =

( ii ) If you want to store the values 7 and 12 in MATLAB variables a & b and store the values of
their product and division in c and d, do as follows:

>> a =7 <ENTER>

a=

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

>>b =12 <ENTER>

b=

12

>>c= a*b <ENTER>

c=

84

>>d = 12/7 <ENTER>

d=

1.7143

You can exit MATLAB with the command exit or quit. A computation can be stopped with

[ctrl-c]

Variables, Expressions & Statements:

Variable names must be a single word containing no space and up to 31 characters. Variables
names are case sensitive and a variable name must start with a letter. Punctuation characters
are not allowed.

MATLAB’s statements are of the form:

>> variables = expression or

>> expression

Expressions are composed of operators, function and variable names. After evaluation
the value is assigned to the variable and displayed. If the variable name and = sign are omitted,
a variable ans (for answer) is automatically created and the result is assigned to it.

A statement is normally terminated with the carriage returns. However, a statement can
be continued on the next line with three or more periods followed by a carriage return. Several
statements can be placed on a single line if separated by commas or semicolons. If the
last character of a statement is a semicolon, then values of the variable printing to the screen
will be suppressed, but the assignment is still carried out.

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

Rules of Precedence:

Expressions are evaluated from left to right with exponential operation having the
highest precedence, followed by multiplication and division having equal precedence, followed
by addition and subtracting having equal precedence. Parentheses can be used to alter
this ordering in which case these rules of precedence are applied within each set of
parentheses starting with the innermost set and proceeding outward.

( iii ) The most recent values assigned to the variables you used in the current session
are available. For example, if you type a at the prompt you get the output as :

>> a

a=

If you cannot remember the names of the variables, you have used in the current session, you
can use the who command for a list of variables it has in the current session.

>> who

Your variables are

ans a b cd

The command whos will list the variables in the workspace and their size. The command

>> clear

will remove all current variables from the memory of the system.

>> clear a

will clear only the variable a.

( iv) To recall previous commands, MATLAB uses the cursor keys , , , on your
keyboard.

- recalls the most recent command to the MATLAB prompt.

- scrolls forward through commands.

- moves one within a command at the MATLAB prompt.

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

( v ) The display of numerical values can have different format as we see below:

>> e= 1/3 e =

0.3333

>> format long (long decimal format)

>> e

e=

0.33333333333333

>> format short e (short exponential format)

>> e

e=

3.3333 e-01

>>format long e (long exponential format)

e=

3.33333333333333 e-04

>>format ( default format)

>>e

e=

0.3333

( vi ) To suppress the display of output of a command on screen put semicolon ‘;’ after the
command.

>> a=3;

>>

( vii ) To end a session, type quit or exit at the MATLAB prompt.

>> exit

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

When we log out or exit, MATLAB will lose all the current variables from the memory.
To save the current session, type

>> save

This saves the all current variables to a binary diskfile matlab.mat. When you later re-
enter

MATLAB, the command

>> load

will restore the workspace to list former state.

( viii ) Complex numbers i or j stands for √−1 and pi gives the value of .

>> c = 1-2i

c=

1.000–2.0000 i

Some functions deal with complex numbers are as follows:

>> abs ( c )

ans =

2.2361

>> real ( c )

ans =

>> imag ( c )

ans =

-2

>> angle ( c )

ans =

-1.1071

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

Information about any command or operation is available by typing:

>> help command

and to get menu of help commands type

>> help

3. WORKING WITH MATRICES:

MATLAB works with essentially only one kind of objects, i.e. a rectangular numerical matrix

with possibly complex entries. All variables represent matrices.

Scalers - 1 by 1 matrix

Row vector - matrix with one row

Column vector - matrix with one column.

If you want to store a matrix 1 2 3 in a variable a in the MATLAB’s current

4 5 6

7 8 9

memory, you type the following in the MATLAB prompt.

>> a = [1 2 3; 4 5 6; 7 8 9]

a=

1 2 3

4 5 6

7 8 9

The rows are separated by semicolons and elements are separated by space or by comma. That
is, the above matrix can also be stored by the following command.

>> a = [1,2,3;4,5,6;7,8,9];

or by the statement

>> a = [

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

1 2 3

4 5 6

7 8 9 ];

The semicolon at the end of a command suppresses the output.

The matrix a is transposed and is stored in b by the following command

>> b = a’

b=

1 4 7

2 5 8

3 6 9

The following matrix operations are available in MATLAB

Function Task

+ Addition

- Subtraction

* Multiplication

^ Power

‘ Transpose

\ Left Division

/ Right Division

Examples:

>> a1 = a+b (matrices a and b are added and stores in a1)

a1 =

2 6 10

6 10 14

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

10 14 18

>> b1 = a-b (b is subtracted from a and stores in b1)

b1 =

0 -2 -4

2 0 -2

4 2 0

>> c = a*b (a is multiplied with b and stores in c)

c=

14 32 50

32 77 122

50 122 194

The operations *, ^, \, / can be made to operate entry-wise by preceding them by a period.

>> [ 1 2 3 4] .* [1 2 3 4] (element-wise product)

ans =

1 4 9 16

>> [1 2 3 4] .^ 2 (element-wise power)

ans =

1 4 9 16

>> m = [ 2 1 5; 5 4 9;8 6 3];

>> n = inv(m) (Computes the inverse of the matrix a)

n=

1.1351 -0.7297 0.2973

-1.5405 0.9189 -0.1892

0.0541 0.1081 -0.0811

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

>> l = det(m) (Computes the determinant of a)

l=

-37

>> eig(a) (display eigen values of a)

ans =

16.1168

-1.1168

0.0000

>> [v,d]=eig(a) (gives eigen values and eigen vectors vof a)

v=

0.2320 0.7858 0.4082

0.5253 0.0868 -0.8165

0.8187 -0.6123 0.4082

d=

16.1168 0 0

0 -1.1168 0

0 0 0.0000

>> size(a) (gives size of the matrix a)

ans =

3 3

>> rank(a) (Displays rank of a)

ans =

>> clear (Clear’s All variables a, b, c, a1, b1, d)

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

>>clc (Clears Screen)

The following are some special matrices generated by built-in statements and functions

>> a = magic(4) (Produces Magic square of size 4)

a=

16 2 3 13

5 11 10 8

9 7 6 12

4 14 15 1

>> b = rand(5) (Generates Random matrix of size 5)

b=

0.9501 0.7621 0.6154 0.4057 0.0579

0.2311 0.4565 0.7919 0.9355 0.3529

0.6068 0.0185 0.9218 0.9169 0.8132

0.4860 0.8214 0.7382 0.4103 0.0099

0.8913 0.4447 0.1763 0.8936 0.1389

>> a = hilb(5)

a=

1.0000 0.5000 0.3333 0.2500 0.2000

0.5000 0.3333 0.2500 0.2000 0.1667

0.3333 0.2500 0.2000 0.1667 0.1429

0.2500 0.2000 0.1667 0.1429 0.1250

0.2000 0.1667 0.1429 0.1250 0.1111

is the Hilbert matrix, the king of ill-conditioned matrix of order 5.

>> ones(5) (generates square matrix of order 5 with all entries 1)

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

ans =

1 1 1 1 1

1 1 1 1 1

1 1 1 1 1

1 1 1 1 1

1 1 1 1 1

>> zeros(6) (generates matrix with all entries zero)

ans =

0 0 0 0 0 0

0 0 0 0 0 0

0 0 0 0 0 0

0 0 0 0 0 0

0 0 0 0 0 0

0 0 0 0 0 0

Matrix building functions

1. eye(n) - Identity matrix of order n

2. diag(a) - Vector consisting of diagonal of a

3. triu(a) - Upper triangular part of a

4. tril(a) - Lower triangular part of a

We can also load a matrix from an external ASCII file, say data.ext (where .ext is any extension).
If this ascii file contain a rectangular array of just the numeric matrix entries, then to load the
matrix type the command

Submatrices and Colon Notation

Consider a matrix a give by

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

>> a = [1 2 3 4;5 6 7 1;2 3 4 5]

a=

1 2 3 4

5 6 7 1

2 3 4 5

>> b= a(1:2,3) (Vector consisting of the first 2 entries of the 3rd column of a)

b=

>>c = a(:,3) (Vector consisting of 3rd column of a)

c=

>> d = a(1:2,:) (First two rows)

d=

1 2 3 4

5 6 7 1

>> e = a(3,:) (Third row of a)

e=

2 3 4 5

>> f = a(:,[2 4]) (Columns 2 and 4)

f=

2 4

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

6 1

3 5

>> aa = a(1:2, 3:4) (Submatrix)

aa =

3 4

7 1

Matrices can be built from blocks of matrices

>> a = [1 2 3;4 5 6;7 8 9]

>> b = [a, zeros (3,2); ones(2,3),eye(2)] ( will build a 5 by 5 matrix)

b=

1 2 3 0 0

4 5 6 0 0

7 8 9 0 0

1 1 1 1 0

1 1 1 0 1

Functions of vectors

>> t = [1:2:10] (Makes a row vector t having element starting from 1 up to 10 with step size 2)

t=

1 3 5 7 9

>> tt = [5:-1:0] (Here increment is –1)

tt =

5 4 3 2 1 0

>> x = 1:.2:2 (Here increment is not an integer)

x=

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

1.0000 1.2000 1.4000 1.6000 1.8000 2.0000

>> max(t) (maximum element in the vector t)

ans =

>> min(t) (minimum element in the vector t)

ans =

>> sum(t) (sum of all elements in the vector t)

ans =

25

>> mean(t) (mean of elements of t)

ans =

>>sort(t) (arrange in ascending order)

ans =

1 3 5 7 9

>> prod(t) (Product of elements)

ans =

945

>> median(t) (computes median)

ans =

>> any(t)

ans =

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

>> all(t)

ans =

>> std(t) (standard deviation)

ans =

3.1623

4.Plotting Graphs

2-D plots :

Suppose we want to plot the graph of y = sin(x), in a interval [0,10]. Type as follows

>> x = 0:0.5:10; (generates points in the given interval)

>> y = sin(x); (calculate function values at the x points)

>> plot(x,y) (Plots x verses y)

This will display the following graph:

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

We can also give the title, x-label, y-label to the graph, to do this you type as follows
on

MATLAB command prompt:

>> title(‘Graph Of Sine Function’);

>>xlabel(‘X Values’);

>>ylabel(‘Y=Sin(x)’);

It will display the graph as follows:

More on plots

plot(x,y) plots vector y versus vector x.

If x or y is a matrix, then the vector is plotted versus the rows or columns of the matrix,
whichever line up.

plot(y) plots the columns of y versus their index.

If y is complex, plot(y) is equivalent to plot(real(y),imag(y)).

In all other uses of plot, the imaginary part is ignored. various line types, plot symbols and
colors may be obtained with plot(x,y,s) where s is a character string made from one element
from any or all the following columns:

y yellow . point - solid m magenta

o circle : dotted c cyan x x-mark

-. dashdot r red + plus -- dashed

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

G green * star b blue s square

w white d diamond k black v triangle (down)

^ triangle (up) < triangle (left) > triangle (right) p pentagram

H hexagram

Example:

plot(x,y,'c+:') plots a cyan dotted line with a plus at each data point.

plot(x,y,'bd') plots blue diamond at each data point but does not draw any line.More
than one plot in the same graph

>> plot(x, y, ‘b’, x, z, ‘g’)

puts two plots, plot(x, y, ‘b’) and plot(x, z, ‘g’) in one graph. The first one with blue color and
the second with green color.

Example:

>> t = linspace(0,2*pi); (line space generates 100 t points between 0 and 2 )

>> x = sin(t);

>> y = cos(t);

>> plot(t, x,’*’, t, y,’-’) (plots sine and cos graphs in the same plot)

>> legend(‘x = sin(t)’, ’y = cos(t)’) (provides legends for graphs)

>> grid (provides grid lines)

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

plot(x1,y1,s1,x2,y2,s2,x3,y3,s3,...) combines the plots defined by the (x,y,s) triples, where the
x's and y's are vectors or matrices and the s's are strings.

plot(x,y,'y-',x,y,'go') plots the data twice, with a solid yellow line interpolating green circles at
the data points.

Subplots

You can hold more than one set of axes on one figure window. The command
subplot(m,n,p) subdivides the current figure window into an m-by-n matrix of plotting areas
and chooses the pth area to be active.

Example:

>> x = -2*pi:pi/10:2*pi;

>> y = x.^2;

>> z = sin(x);

>> y1 = cos(x);

>> z1 = exp(x);

>> subplot(2,2,1),plot(x,y)

>> grid

>> subplot(2,2,2),plot(x,z)

>> grid

>> subplot(2,2,3),plot(x,y1)

>> grid

>> subplot(2,2,4),plot(x,z1)

>>grid

It displays the graph as follows:

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

Functions for 2-D plots

Function Task Function Task

plot Linear plot hold Hold current graph

loglog Log-log scale plot axes Create axes in

arbitrary positions

semilogx Semi-log scale plot subplot Create axes in tiled

positions

semilogy Semi-log scale plot legend Graph legend

polar Polar coordinate plot title Graph title

Function Task Function Task

plotyy Graphs with y tick labels on the left and right

axis Control axis scaling and appearance

zoom Zoom in and out on a 2-D plot

xlabel X-axis label

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

ylabel Y-axis label

text Text annotation

grid Grid lines gtext Place text with mouse

box Axis box

MATLAB Programming

We can also do programming in MATLAB as we are doing in FORTRAN, C & C++. To make a file
in MATLAB we have to click on “New” in the file menu in menubar. It will open a new file as we
are doing in “word”; and if we save this file (called m-file), will be saved in “bin” folder of
MATLAB.

Such files are called “M-files” because they have an extension of “.m” in its filename. Much of

your work with MATLAB will be creating and refining M-files.

There are two types of M-files: Script Files and Function Files

Script Files

A script file consists of a sequence of normal MATLAB statements. If the file has the filename,
say, rkg.m, then the MATLAB command >> rkg will cause the statements in the file to be
executed. Variables in a script file are global and will change the value of variables of the same
name in the environment of the current MATLAB session.

Script files are often used to enter data into a large matrix; in such a file, entry errors can be
easily edited out.

Example: In a file rkg.m enter the following:

% This is a sample m-file a = [1,2,3;0,1,1;1,2,3]

b =a’;

c = a+b

d = inv(c)

save this file. Then to execute this file, type

>> rkg <ENTER>

a=

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

1 2 3

0 1 1

1 2 3

b=

1 0 1

2 1 2

3 1 3

c=

2 2 4

2 2 3

4 3 6

d=

-1.5000 0 1.0000

0 2.0000 -1.0000

1.0000 -1.0000 0

The % symbol indicates that the rest of the line is a comments. MATLAB will ignore the rest of
the line. However, the first comment lines which document the m-file are available to the on-
line help facility and will be displayed

A M-file can also reference other M-files, including referencing itself recursively.

Function Files

Function files provide extensibility to MATLAB. You can create new functions specific to your
problem which will then have the same status as other MATLAB functions. Variables in a
function file are by default local. However, you can declare a variable to be global if you wish.

Example

function y = prod (a,b)

y = a*b;

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

Save this file with filename prod.m then type on the MATLAB prompt

>> prod (3,4)

ans =

12

In MATLAB to get input from user the syntax rule is :

variable name = input (‘variable’);

As we know that if we don’t write “;” after a statement in MATLAB, it will print the output also.
That means if in a programme we write:

a=input (‘ Enter a number ‘);

And on command prompt if we run this program it will be displayed like:

>> Enter a number

If we type 2 at the cursor then we get the output as a=2

Control Flow

MATLAB offers the following decision making or control flow structures:

1. If- Else –End Construction

2. For loops

3. While loops

4. Switch-Case constructions etc.

SYNTAX RULE FOR CONTROLLING THE FLOW:

1) if statement condition:

The general form of the if statement is:

if expression

statements

elseif expression

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

statements

else

statements

end

The statements are executed if the real part of the expression has all non-zero elements. The

else and elseif parts are optional. zero or more elseif parts can be used as well as nested if's.
The expression is usually of the form

expr rop expr

where rop is ==, <, >, <=, >=, or ~=.

Example:

if i == j

a(i,j) = 2;

elseif abs(i-j) == 1 a(i,j) = -1;

else

2) else used with if:

else is used with if. The statements after the else are executed if all the preceding if
and

elseif expressions are false.

The general form of the if statement is:

if expression

statements

elseif expression

statements

else

statements

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

end

3) elseif if statement condition:

elseif is used with if. The statements after the elseif are executed if the expression is true and
all the preceding if and elseif expressions are false. An expression is considered true if the real
part has all non-zero elements. elseif does not need a matching end, while else if does.

the general form of the if statement is:

if expression

statements

elseif expression

statements

else

statements

end

4) end terminate scope of for, while, switch, try, and if statements. Without end's, for, while,
switch, try, and if wait for further input. each end is paired with the closest previous unpaired
for, while, switch, try or if and serves to terminate its scope. end can also serve as the last index
in an indexing expression. in that context,

end = size(x,k) when used as part of the k-th index. examples of this use are, x(3:end)
and x(1,1:2:end-1). when using end to grow an array, as in x(end+1) = 5, make sure x exists
first.

5) for repeat statements a specific number of times:

The general form of a for statement is:

for variable = expr, statement, ..., statement

end

The columns of the expression are stored one at a time in the variable and then the following

statements, up to the end, are executed. The expression is often of the form x:y, in which
case its columns are simply scalars. some examples

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

Example: (assume n has already been assigned a value)

for i = 1:n,

for j = 1:n,

a(i,j) = 1/(i+j-1);

end

end

for s = 1.0: -0.1: 0.0, end steps s with increments of -0.1 for e = eye(n), ... end sets e to the unit
n-vectors.

Long loops are more memory efficient when the colon expression appears in the for statement
since the index vector is never created.

6) The break statement can be used to terminate the loop prematurely. break terminate
execution of while or for loop. In nested loops, break exits from the innermost loop only.

7) while repeat statements an indefinite number of times.

The general form of a while statement is:

while expression

statements

end

The statements are executed while the real part of the expression has all non-zero elements.
The expression is usually the result of expr rop expr where rop is ==, <, >, <=, >=, or ~=.

Example:

(assuming a already defined)

e = 0*a; f = e + eye(size(e)); n = 1;

while norm(e+f-e,1) > 0, e = e + f;

f = a*f/n;

n = n + 1;

end

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

8) switch switches among several cases based on expression:

the general form of the switch statement is:

switch switch_expr case case_expr, statement, ..., statement

case {case_expr1, case_expr2, case_expr3,...}

statement, ..., statement

...

otherwise,

statement, ..., statement

end

The first case where the switch_expr matches the case_expr is executed. when the
case expression is a cell array (as in the second case above), the case_expr matches if
any of the elements of the cell array match the switch expression. If none of the case
expressions match the switch expression then the otherwise case is executed (if it
exists). Only one case is executed and execution resumes with the statement after the
end. the switch_expr can be a scalar or a string. A scalar switch_expr matches a
case_expr if switch_expr==case_expr. A string switch_expr matches a case_expr if
strcmp(switch_expr,case_expr) returns 1 (true).

Example:

(assuming method exists as a string variable):

switch lower(method)

case {'linear','bilinear'}, disp('method is linear')

case 'cubic', disp('method is cubic') case 'nearest', disp('method is nearest') otherwise,


disp('unknown method.')

end

9) case switch statement case:

case is part of the switch statement syntax, whose general form is:

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

switch switch_expr case case_expr, statement, ..., statement

case {case_expr1, case_expr2, case_expr3,...}

statement, ..., statement

...

otherwise,

statement, ..., statement

end

10) otherwise default switch statement case.

otherwise is part of the switch statement syntax, whose general form is:

switch switch_expr case case_expr, statement, ..., statement

case {case_expr1, case_expr2, case_expr3,...}

statement, ..., statement

...

otherwise,

statement, ..., statement

end

The otherwise part is executed only if none of the preceding case expressions match the
switch expression.

11) try begin try block:

The general form of a try statement is:

try, statement, ..., statement, catch, statement, ..., statement end

Normally, only the statements between the try and catch are executed. however, if an error
occurs while executing any of the statements, the error is captured into lasterr and the
statements between the catch and end are executed. if an error occurs within the
catch statements, execution will stop unless caught by another try...catch block. The
error string produced by a failed try block can be obtained with lasterr.

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

12) catch begin catch block:

The general form of a try statement is:

try statement, ..., statement, catch statement, ..., statement end

13) return returns to invoking function:

return causes a return to the invoking function or to the keyboard. it also terminates the
keyboard mode.

normally functions return when the end of the function is reached. a return statement can be
used to force an early return.

Example:

function d = det(a)

if isempty(a) d = 1; return

else

...

end

How to run a program in MATLAB?

Suppose we have created a m-file & saved. Now to run this program, on command prompt type
the file name and just press the ENTER KEY that will run the file.

Data File:

Now to make a data file in MATLAB, we just make a file in which all the data are stored. Now
we make another file in which the operation on that data is to be done. Then in this file, where
we have to call that data we have to just type the file name of the file in which data is stored
and write the rest of the programming statements. So when run this file the file in which data is
stored will be called and then rest of the programming statements are executed & finally we
get the output.

MEX-Files:

We can call our C programs from MATLAB as if they were built in functions. Those
programs in C which are callable in MATLAB are referred as MEX-Files. MEX-files are

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

dynamically linked subroutines that the MATLAB interpreter can automatically load & execute.
For example the following program in C to add two integers having file name “add”.

#include<stdio.h>

main( )

{ int a=2,b=3;

d=a+b;

printf(‘sum is:’,d);

return 0;

To compile & link this example at the MATLAB prompt, type

>>mex add.c

and press the “ENTER”key, it will give the output.

Some useful commands for programming:

>> echo on --- Echoing of commands in all script files

>> echo off --- Turns off echo

>> echo on all --- turns on of command including function files

>> disp(‘Any string’) --- Displays the string

>> diary file --- Causes copy of all subsequent keyboard input and most of the
resulting output (but not graphs) to be written on the named file.

>> pause --- causes to stop execution of until any key is pressed.

Some Examples:

1) Example for if, else

for i = 1:n

for j = 1:n

if i==j

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

a(i, j) = 2

elseif abs(i – j) ==1

a(i, j) = -1;

else

a(i, j) = 0;

end

end

end

2) Example for while

eps = 1

while (1+eps)>1

eps = eps/2;

end

eps = eps*2

3) Gauss Elimination Method

function [x] = gausselim(A,b)

% This subroutine will perform Gaussian elimination on the matrix you pass and solve %

the system AX = b

N = max(size(A))

for j = 2:N

for i = j:N

m = A(j,j-1) / A(j-1,j-1);

A(i, :) = A(i, :) – A(j-1,:)*m;

b(i) = b(i) – m*b(j-1);

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

end

end

%Perform back substitution

x = zeros(N, 1)

x(N) = b(N) / A(N, N)

for j = N-1:-1:1

x(j) = (b(j)-A(j,j+1:N)) / A(j, j)

end

RELATIONAL OPERATORS

MATLAB relational operators can be used to compare two arrays of the same size, or to
compare an array to a scalar. When we compare an array to a scalar, scalar expansion is used to
compare the scalar to each array element and the result has the same size as the array.

NOTE: = and == mean two different things:

== compares two variables and returns ones where they are equal and zeros where they are
not; while, = is used to assign the output of an operation to a variables.

Example:

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

>> a = 1:0.5:10;

>> b = 5:0.5:14;

>> c = a > 5 c =

Columns 1 through 12

0 0 0 0 0 0 0 0 0 1 1 1

Columns 13 through 19

1 1 1 1 1 1 1

>> d = (a ==b)

d=

Columns 1 through 12

0 0 0 0 0 0 0 0 0 0 0 0

Columns 13 through 19

0 0 0 0 0 0 0

LOGICAL OPERATORS

Example:

>> a = 1:15;

>> b = ~ ( a < 5 )

b=

Columns 1 through 12

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

0 0 0 0 1 1 1 1 1 1 1 1

Columns 13 through 15

1 1 1

>> c = ( a > 2 ) & (a < 8 )

c=

Columns 1 through 12

0 0 1 1 1 1 1 0 0 0 0 0

Columns 13 through 15

0 0 0

>> d = ( a > 2 ) | ( a < 8 )

d=

Columns 1 through 12

1 1 1 1 1 1 1 1 1 1 1 1

Columns 13 through 15

1 1 1

Solving ordinary differential equation:

We can solve a system of differential equations using MATLAB, the function names for

that are ode45, ode23, ode113 etc. Out of which we are going to concentrate on ode45 only,
and the syntax rule for that is:

>> [x , t]=ode45(‘filename’,tspan,x0)

Suppose we have to solve: dx1/dt = -x1(t)-t2 x2(t) ; dx2/dt = -t2x1(t)-x2(t) x1(0)=1 x2(0)=1 on
[0,1].

Here we have to create a new file suppose the file name is orddiff.m. In that file we have to
write the above system of differential equation, and for that we write a function:

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

function y = filename (t, x)

y = [system of differential equations]

i.e. we write :

function y = orddiff(t,x)

y = [-x(1)-t .^2*x(2); -t .^2*x(1)-x(2)]

After doing this go to command prompt. Here initial conditions are [1 1]’ so our x0=[1 1]’ and
we have to solve this ode on [0 1] so our tspan=[0 1], then

>> [x t] = ode45(‘orddiff’,tspan,x0)

will solve this system of differential equations.

Finding minimum of a function:

We can find minimum of a function in an interval using MATLAB, the function names for that

are fmin, fmins. Here we give example of fmin only, the syntax rule for that is:

>> X= fmin(‘filename’,x1,x2)

Suppose we have to find minimum of :

f(x) = x.^2 over the interval [2, 4]

Here we have to create a new file suppose the file name is rkgmin.m. In that file we have to
write the above function, and for that we write a function:

function y = filename (x)

y = function i.e. we write :

function y = rkgmin(x)

y = x .^2;

After doing this go to command prompt. Here the interval on which we have to find the
minimum is [2, 4] so our x1 = 2 and x2 = 4. On command prompt now you type:

>>X = fmin(‘rkgmin’,x1,x2)

will solve this system of differential equations.

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

Communication Tool Box

The Communications Toolbox extends the MATLAB technical computing environment with
functions, plots, and a graphical user interface for exploring, designing, analyzing, and
simulating algorithms for the physical layer of communication systems. The toolbox helps you
create algorithms for commercial and defense wireless or wireline systems.

The key features of the toolbox are

Functions for designing the physical layer of communications links, including source
coding, channel coding, interleaving, modulation, channel models, and equalization

Plots such as eye diagrams and constellations for visualizing communications signals Graphical
user interface for comparing the bit error rate of your system with a wide variety of
proven analytical results

In most media for communication, only a fixed range of frequencies is available for
transmission. One way to communicate a message signal whose frequency spectrum does
not fall within that fixed frequency range, or one that is otherwise unsuitable for the channel, is
to alter a transmittable signal according to the information in your message signal. This
alteration is called modulation, and it is the modulated signal that you transmit. The
receiver then recovers the original signal through a process called demodulation. The
contents of this tool box are as follows.

Modulation Features of the Toolbox--Overview of the modulation types and


modulation operations that the Communications Toolbox supports

Modulation Terminology--Definitions of terms, as well as inequalities that certain


modulation quantities must satisfy

Analog Modulation--Representing analog signals and performing analog modulation Digital


Modulation—Representing digital signals, representing signal constellations for digital
modulation, and performing digital modulation

This section describes how to represent analog signals using vectors or matrices. It
provides examples of using the analog modulation and demodulation functions.
Representing Analog Signals To modulate an analog signal using this toolbox, start with a real
message signal and a sampling rate Fs in hertz. Represent the signal using a vector x, the entries
of which give the signal's values in time increments of 1/Fs. Alternatively, you can use a

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

matrix to represent a multichannel signal, where each column of the matrix represents
one channel.

Analog Modulation/Demodulation function lists


amdemod-- Amplitude demodulation
ammod-- Amplitude modulation
fmdemod-- Frequency demodulation
fmmod-- Frequency modulation
pmdemod-- Phase demodulation
pmmod-- Phase modulation
ssbdemod-- Single sideband amplitude demodulation
ssbmod-- Single sideband amplitude modulation

amdemod [Amplitude demodulation]


Syntax
z = amdemod(y,Fc,Fs)
z = amdemod(y,Fc,Fs,ini_phase)
z= amdemod(y,Fc,Fs,ini_phase,carramp)
z = amdemod(y,Fc,Fs,ini_phase,carramp,num,den)
Description:
z = amdemod(y,Fc,Fs) demodulates the amplitude modulated signal y from a
carrier signal with frequency Fc (Hz). The carrier signal and y have sample frequency Fs
(Hz). The modulated signal y has zero initial phase and zero carrier amplitude, so
it represents suppressed carrier modulation. The demodulation process uses the
lowpass filter specified by [num,den] = butter(5,Fc*2/Fs).Note
The Fc and Fs arguments must satisfy Fs > 2(Fc + BW) where BW is the bandwidth of the
original signal that was modulated.z = amdemod(y,Fc,Fs,ini_phase) specifies the
initial phase of the modulated signal in radians.z =
amdemod(y,Fc,Fs,ini_phase,carramp) demodulates a signal that was created via
transmitted carrier modulation instead of suppressed carrier modulation. carramp is
the carrier amplitude of the modulated signal.
z = amdemod(y,Fc,Fs,ini_phase,carramp,num,den) specifies the numerator
and denominator of the lowpass filter used in the demodulation.

ammod [Amplitude modulation]


Syntax
y = ammod(x,Fc,Fs)
y = ammod(x,Fc,Fs,ini_phase)
y = ammod(x,Fc,Fs,ini_phase,carramp)

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

Description:
y = ammod(x,Fc,Fs) uses the message signal x to modulate a carrier signal with
frequency Fc (Hz) using amplitude modulation. The carrier signal and x have
sample frequency Fs (Hz). The modulated signal has zero initial phase and zero carrier
amplitude, so the result is suppressed-carrier modulation.Note The x, Fc, and Fs input
arguments must satisfy Fs > 2(Fc + BW), where BW is the bandwidth of the
modulating signal x.y = ammod(x,Fc,Fs,ini_phase) specifies the initial phase in the
modulated signal y in radians.y = ammod(x,Fc,Fs,ini_phase,carramp) performs
transsmitted-carrier modulation instead of suppressed-carrier modulation. The
carrier amplitude is carramp.

fmmod [Frequency modulation]


Syntax
y = fmmod(x,Fc,Fs,freqdev)
y = fmmod(x,Fc,Fs,freqdev,ini_phase)
Description:
y = fmmod(x,Fc,Fs,freqdev) modulates the message signal x using frequency
modulation. The carrier signal has frequency Fc (Hz) and sampling rate Fs (Hz), where Fs
must be at least 2*Fc. The freqdev argument is the frequency deviation (Hz) of
the modulated signal.y = fmmod(x,Fc,Fs,freqdev,ini_phase) specifies the initial
phase of the modulated signal, in radians.

Fmdemod[ Frequency demodulation]


Syntax
z = fmdemod(y,Fc,Fs,freqdev)
z = fmdemod(y,Fc,Fs,freqdev,ini_phase)
Description:
z = fmdemod(y,Fc,Fs,freqdev) demodulates the modulating signal z from the carrier
signal using frequency demodulation. The carrier signal has frequency Fc (Hz) and
sampling rate Fs (Hz), where Fs must be at least 2*Fc. The freqdev argument is the
frequency deviation (Hz) of the modulated signal y.z =
fmdemod(y,Fc,Fs,freqdev,ini_phase) specifies the initial phase of the modulated signal,
in radians.

Pmmod [Phase modulation]


Syntax
y = pmmod(x,Fc,Fs,phasedev)
y = pmmod(x,Fc,Fs,phasedev,ini_phase)

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

Description
y = pmmod(x,Fc,Fs,phasedev) modulates the message signal x using phase modulation.
The carrier signal has frequency Fc (Hz) and sampling rate Fs (Hz), where Fs must be at
least 2*Fc. The phasedev argument is the phase deviation of the modulated signal in
radians.y = pmmod(x,Fc,Fs,phasedev,ini_phase) specifies the initial phase of the
modulated signal in radians.

pmdemod [Phase demodulation]


Syntax:
z = pmmod(y,Fc,Fs,phasedev)
z = pmmod(y,Fc,Fs,phasedev,ini_phase)
Description:
z = pmmod(y,Fc,Fs,phasedev) demodulates the phase-modulated signal y at the
carrier frequency Fc (Hz). z and the carrier signal have sampling rate Fs (Hz), where Fs
must be at least 2*Fc. The phasedev argument is the phase deviation of the
modulated signal, in radians.z = pmmod(y,Fc,Fs,phasedev,ini_phase) specifies the
initial phase of the modulated signal, in radians.

ssbdemod [Single sideband amplitude demodulation]


Syntax :
z = ssbdemod(y,Fc,Fs)
z = ssbdemod(y,Fc,Fs,ini_phase)
z = ssbdemod(y,Fc,Fs,ini_phase,num,den)
Description:
For All Syntaxesz = ssbdemod(y,Fc,Fs) demodulates the single sideband
amplitude modulated signal y from the carrier signal having frequency Fc (Hz). The
carrier signal and y have sampling rate Fs (Hz). The modulated signal has zero initial
phase, and can be an upper- or lower-sideband signal. The demodulation process uses
the lowpass filter specified by [num,den] = butter(5,Fc*2/Fs).Note The Fc and Fs
arguments must satisfy Fs > 2(Fc + BW), where BW is the bandwidth of the
original signal that was modulated.z = ssbdemod(y,Fc,Fs,ini_phase) specifies the
initial phase of the modulated signal in radians.z = sbdemod(y,Fc,Fs,ini_phase,num,den)
specifies the numerator and denominator of the lowpass filter used in the
demodulation.

Ssbmod [Single sideband amplitude modulation]


Syntax
y = ssbmod(x,Fc,Fs)

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

y = ssbmod(x,Fc,Fs,ini_phase)
y = ssbmod(x,fc,fs,ini_phase,'upper')
Description:
y = ssbmod(x,Fc,Fs) uses the message signal x to modulate a carrier signal with
frequency Fc (Hz) using single sideband amplitude modulation in which the lower
sideband is the desired sideband. The carrier signal and x have sample frequency Fs
(Hz). The modulated signal has zero initial phase. y = ssbmod(x,Fc,Fs,ini_phase) specifies
the initial phase of the modulated signal in radians.y = ssbmod(x,fc,fs,ini_phase,'upper')
uses the upper sideband as the desired sisedband.

QUESTIONS:

1 . What are the application areas of MATLAB?

2. List out types of file in MATLAB.

3. How to generate x and y coordinates of 100 equidistant points on a unit circle?

4. How to do array operations?

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess


COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB

Interpretation of the Results: (Discuss results and (if any) theoretical concepts that are
related to this activity.)

Conclusion: (Write down your conclusions, things learned, problems encountered during the lab
and how they were solved, etc.)

Additional requirements in Lab Report:

1. Make screen captures of procedures of the activity

2. Make a good selfie with your screen doing the Lab activity.

3. Include all the images in your Lab Report.

Note: Also attached/submit lab files along with the Lab Report.

COMMUNICATION 1: PRINCIPLES OF COMMUNICATION SYSTEMS LAB| froyd wess

You might also like