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

DSP Lab Manual Part-1 v Sem 22 Batch SPC 511 EC 2024-2025[1]

Uploaded by

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

DSP Lab Manual Part-1 v Sem 22 Batch SPC 511 EC 2024-2025[1]

Uploaded by

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

DSP LAB MANUAL

INTRODUCTION
Introduction to MATLAB and Creation of File using Basic commands.
Introduction:

MATLAB is a high-performance language for technical computing. It integrates computation,


visualization, and programming in an easy-to-use environmentwhere problems and solutions are
expressed in familiar mathematical notation.
The name MATLAB stands for matrix laboratory. MATLAB was originally written to provide
easy access to matrix.

Starting and Quitting MATLAB:

• To start MATLAB, double-click the MATLAB shortcut icon on yourWindowsdesktop. You


will know MALTAB is running when you see the special" >> " prompt in the MATLAB
Command Window.

• To end your MATLAB session, select Exit MATLAB from the File menu in the desktop, or
type quit (or exit) in the Command Window, or with easy way by click on close button in
control box.

Desktop Tools
1- Command Window: Use the Command Window to enter variables and runfunctions and
M-files.
2- Command History: Statements you enter in the Command Window are logged in the
Command History. In the Command History, you can view previously run statements, and copy
and execute selected statements.
3- Current Directory Browser: MATLAB file operations use the current directory reference
point. Any file you want to run must be in the current directory or on the search path.
4- Workspace: The MATLAB workspace consists of the set of variables (named arrays) built
up during a MATLAB session and stored in memory.

V SEMESTER 22 Batch
1
DSP LAB MANUAL

5.Editor/Debugger Window: Use the Editor/Debugger to create and debug


M-files.

Applications:
• Mathematical operations
• Vector
• Matrices and Matrix operations
• Solving systems of linear equations
• Plotting
• Curve fitting, Interpolation
• Solving Ordinary Differential Equations
• In Image processing, DSP, Speech Processing, communications.

V SEMESTER 22 Batch
2
DSP LAB MANUAL

Basic Commands

clear Command: Removes all variables from workspace.


clc Command: Clears the Command window and homes the cursor.
help Command: help <Topic> displays help about that Topic if it exists.
Look for Command: Provides help by searching through all the first lines of MATLAB
help topics and returning those that contains a key word youspecify.
edit Command: enable you to edit (open) any M-file in Editor Window. This command
doesn’t open built-in function like, sqrt. See also type Command.
more command: more on enables paging of the output in the MATLABcommand window, and
more off disables paging of the output in the MATLAB command window.

Note:
A semicolon " ; " at the end of a MATLAB statement suppresses printing ofresults.
If a statement does not fit on one line, use " . . . ", followed by Enter toindicate that
the statement continues on the next line. For example:
>> S= sqrt
(225)*30 /...
(20*sqrt (100)
If we don’t specify an output variable, MATLAB uses the variable and (short for answer), to store
the last results of a calculation.
Use Up arrow and Down arrow to edit previous commands you entered inCommand Window.
Insert " % " before the statement that you want to use it as comment; the statement will appear in
green color.

V SEMESTER 22 Batch
3
DSP LAB MANUAL

EXPERIMENT 1
Functional Operations of Matrices.

AIM: - To Perform the basic Functional operations of Matrices using Mat lab.
SOFTWARE REQUIRED: - Mat lab (R2013b)
THEORY:

MATLAB, which stands for MATrix LABoratory, is a state-of-the-art mathematical software


package, which is used extensively in both academia and industry. It is an interactive program
for numerical computation and data visualization, which along with its programming
capabilities provides a very useful tool for almost all areas of science and engineering. Unlike
other mathematical packages, such as MAPLE or MATHEMATICA, MATLAB cannot
perform symbolic manipulations without the use of additional Toolboxes. It remains
however, one of the leading software packages for numerical computation.
As you might guess from its name, MATLAB deals mainly with matrices. A scalar is
a 1-by-1 matrix and a row vector of length say 5, is a 1-by-5 matrix. One of the many
advantages of MATLAB is the natural notation used. It looks a lot like the notation that you
encounter in a linear algebra. This makes the use of the program especially easy and it is what
makes MATLAB a natural choice for numerical computations. The purpose of this experiment
is to familiarize MATLAB, by introducing the basic features and commands of the program.

Matrix Functions:

Much of MATLAB‟ s power comes from its matrix functions. These can be further separated
into two sub-categories.
The first one consists of convenient matrix building functions, some of which are given
below.
1. eye - identity matrix
2. zeros - matrix of zeros
3. ones - matrix of ones
4. diag - extract diagonal of a matrix or create diagonal matrices
5. triu - upper triangular part of a matrix
6. tril - lower triangular part of a matrix
7. rand - randomly generated matrix
eg: diag([0.9092;0.5163;0.2661])
ans =
0.9092 0 0
0 0.5163 0
0 0 0.2661

Commands in the second sub-category of matrix functions are


1. size -size of a matrix
2. det -determinant of a square matrix
3. inv -inverse of a matrix
4. rank -rank of a matrix
5. rref -educed row echelon form

V SEMESTER 22 Batch
4
DSP LAB MANUAL

6. eig –eigen values and eigenvectors


7. poly- characteristic polynomial

PROCEDURE: -
1. Open MATLAB
2. Open New script file
3. Type the program
4. Save in current directory
5. Compile and Run the Program
6. For the output see command window/figure window.
PROGRAM: -
clc;
close all;
clear all;
A=[1,2,3; 3,2,1; 2,1,1];
display('Matrix A');
display(A);
B=[2,1,4; 5,7,2; 6,4,5];
display('Matrix B');
display(B);
C=A';
display('Transpose of Matrix A');
display(C);
D=A*B;
display('Matrix multiplication of A and B');
display(D);
E=A.*B;
display('Bit by bit multiplication of A and B');
display(E);
F=A+B;
display('Addition of A and B');
display(F);
G=det(A);
display('Determinant of A');
display(G);

V SEMESTER 22 Batch
5
DSP LAB MANUAL

H=inv(A);
display('Inverse matrix of A');
display(H);
I=eig(A);
display('Eigen values of A');
display(I);
J=zeros(3,3);
display('Zero matrix');
display(J);
K=ones(3,3);
display('Unity matrix (ones matrix)');
display(K);
L=size(A);
display('Matrix size of A');
display(L);
M=diag(A);
Display(M);
N=eye(3,3);
display('identity matrix');
display(N);
O=triu(A);
display('upper triangular part of matrix');
display(O);
P=tril(A);
display('LOWER triangular part of matrix');
display(P);

Q=trace(A);
display('Trace of matrix');
display(Q);
R=rank(A);
display('Rank of matrix');
display(R);

V SEMESTER 22 Batch
6
DSP LAB MANUAL

OUTPUT: -

Matrix A
A=
1 2 3
3 2 1
2 1 1
Matrix B
B=
2 1 4
5 7 2
6 4 5
Transpose of Matrix A
C=
1 3 2
2 2 1
3 1 1
Matrix multiplication of A and B
D=
30 27 23
22 21 21
15 13 15
Bit by bit multiplication of A and B
E=
2 2 12
15 14 2
12 4 5
Addition of A and B

F=
3 3 7
8 9 3
8 5 6

Determinant of A
G=
-4

V SEMESTER 22 Batch
7
DSP LAB MANUAL

Inverse matrix of A
H=
-0.2500 -0.2500 1.0000
0.2500 1.2500 -2.0000
0.2500 -0.7500 1.0000

Eigen values of A
I=
5.3545
-1.7753
0.4208
Zero matrix
J=
0 0 0
0 0 0
0 0 0
Unity matrix (ones matrix)
K=
1 1 1
1 1 1
1 1 1
Matrix size of A
L=

3 3

M=

1
2
1

Identity matrix

N=
1 0 0
0 1 0
0 0 1

V SEMESTER 22 Batch
8
DSP LAB MANUAL

Upper triangular part of matrix


O=
1 2 3
0 2 1
0 0 1
LOWER triangular part of matrix
P=
1 0 0
3 2 0
2 1 1
Trace of matrix
Q=4
Rank of matrix
R=3

RESULT: - Basic operation on matrices is performed successfully using MATLAB


Commands.

VIVA QUESTIONS:-

1.Expand MATLAB? And importance of MATLAB?2.What is clear all and close all will do?
3. What is disp() and input()?
4. What is the syntax to find the eigen values and eigenvectors of the matrix?
5. What is the syntax to find the rank of the matrix?

V SEMESTER 22 Batch
9
DSP LAB MANUAL

EXPERIMENT-2
Computing the Mathematical Expressions

AIM: - To Perform Computing the Mathematical Expressions using Mat lab.


SOFTWARE REQUIRED: - Mat lab (R2013b)
THEORY:
The expressions consist of the various math functions like as arithmetic, trigonometric,logarithmic,
exponential, constant term value, etc. These functions have proper syntax.
So, you must know the syntax of the mathematical functions. Without this, it will not be easy to
solve the problems in MATLAB.

Let’s see the below syntax for mathematical functions.


Here is different Mathematical functions and their syntax for MATLAB.

• Arithmetic functions
Arithmetic Symbol Operation

+ Addition
– Subtraction
* Multiplication
/ Division
• Trigonometric functions
Trigonometric Symbol Operation / Function

sin(t) Performs Sin operation on variable ‘t’.

cos(t) Performs cosine operation on variable ‘t’.

tan(t) Performs tangent operation on variable ‘t’.

asin(t) Performs arc sin operation on variable ‘t’ or Inverse of the sin function.
acos(t) Performs arc cosine operation on variable ‘t’ or Inverse of the cosfunction.

atan(t) Performs arc tangent operation on variable ‘t’ or Inverse of the


tanfunction.

V SEMESTER 22 Batch
10
DSP LAB MANUAL

Performs exponential operation on variable ‘t’.

• Exponential functions
Exponential Symbol

Operation
exp(t)

• Square functions

^ Power or Square
sqrt(t) Performs square root operation on variable ‘t’.

• Logarithm functions
Symbol Operation

log(t) Performs a natural logarithmic operation on variable ‘t’.

log10(t) Performs a common logarithmic operation on variable ‘t’.


• Maximum & Minimum functions
Symbol Operation

min(t) Finds minimum value from array ‘t’.

max(t) Finds maximum value from array ‘t’.

• Remainder Function
Symbol Operation
Rem(p,q) Gives the remainder after dividing “p” by “q”

• Phase angle function


Symbol Operation

angel(t) Gives phase angle for variable ‘t’.

V SEMESTER 22 Batch
11
DSP LAB MANUAL

• Other useful functions


Symbol Operation

abs(t) Returns absolute value for variable ‘t’.

sign(t) Returns sign of the variable ‘t’.

ceil(t) Returns ceil value for variable ‘t’.

floor(t) Returns floor value for variable ‘t’.

conj(t) Gives complex conjugate of variable ‘t’.

round(t) Returns nearest integer of variable ‘t’.

• Constant term value functions


Symbol / Constant Associated Constant value

Pi The ‘π’ number = 3.14159…

i, j The imaginary unit √-1

Inf The infinity, ∞


These are the mathematical functions representation in the MATLAB.

Programme:

clc;
clear all;
close all;
x=12;
y=10;
a=(2*x)/(4*y);

display(‘value of a’);
display(a);
r=4;

V SEMESTER 22 Batch
12
DSP LAB MANUAL

b=pi*(r^2);
display(‘area of a circle’);
display(b);
m=1;
n=5;
c=(x/2)*((x-y)^2);
display(‘value of c’);
display(c);
t=2;

d = exp (-0.1*t);
display(‘exponential value’);
display(d);
k=13;
l=8;
e= sqrt((x^2)+(y^2));
display(‘value of e’);
display(e);
t=0.1 ;

f= (sin (2*t)+cos(5*t))/2;
display(‘value of f’);
display(f);

Output:

value of a

a=0.6000

area of a circle

b=50.2655

V SEMESTER 22 Batch
13
DSP LAB MANUAL

value of c

c=8

exponential value

d=81.87

value of e

e= 15.2643

value of f

f=0.5381

Result:

Computing the Mathematical Expressions is performed successfully using MATLAB


Commands.

V SEMESTER 22 Batch
14
DSP LAB MANUAL

EXPERIMENT 3

Relational Operations

AIM: - To Perform Relational operations using Mat lab.


SOFTWARE REQUIRED: - Mat lab (R2013b)
THEORY :
Relational operators can also work on both scalar and non-scalar data. Relational operators for
arrays perform element-by-element comparisons between two arrays and return a logical array of
the same size, with elements set to logical 1 (true) where the relation is true and elements set to
logical 0 (false) where it is not.

These operations and functions provide answers to True-False questions. One important use of
this capability is to control the flow or order of execution of a series of MATLAB commands
(usually in an M-file ) based on the results of true/false questions.
As inputs to all relational and logical expressions, MATLAB considers any nonzero
number to be true, and zero to be False. The output of all relational and logical expressions
produces one for True and zero for False, and the array is flagged as logical. That is, the result
contains numerical values 1 and 0 that can be used in mathematical statement, but also allow
logical array addressing.

The following table shows the relational operators −


S.No. Operator & Description

1
< Less than
2
<= Less than or equal to
3
➢ Greater than
4
>= Greater than or equal to
5
== Equal to
6
~= Not equal to

V SEMESTER 22 Batch
15
DSP LAB MANUAL

Apart from the above-mentioned relational operators, MATLAB provides the following
commands/functions used for the same purpose −

Sr.No. Function & Description

1
eq(a, b) Tests whether a is equal to b

2
ge(a, b) Tests whether a is greater than or equal to b

3
gt(a, b) Tests whether a is greater than b

4
le(a, b) Tests whether a is less than or equal to b

5
lt(a, b) Tests whether a is less than b

6
ne(a, b) Tests whether a is not equal to b

7 Isequal Tests arrays for equality

8 Isequaln Tests arrays for equality, treating NaN values as equal

V SEMESTER 22 Batch
16
DSP LAB MANUAL

Program 1:

clc;

clear all;

close all;

X=[1 ,2 ,3;3,4,5;6,7,8];

Y=[4,5,6;6,7,8;8,9,1];

display(X);

display(Y);

K=X>Y;

display(K);

M=[1,2,3;2,3,1;3,1,2];

N=[4,5,6;5,6,7;6,7,8];

display(M);

display(N);

P=M<N;

display(P);

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

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

display(A);

display(B);

Q=A>=B;
V SEMESTER 22 Batch
17
DSP LAB MANUAL

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

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

display(C);

display(D);

R=C<=D;

display(R);

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

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

display(E)

display(F);

S=E==F;

display(S);

Output:

X=1 2 3

345

678

Y=4 5 6

678

891

V SEMESTER 22 Batch
18
DSP LAB MANUAL

K=3x3 logical array

000

000

000

M=1 2 3

2 31

312

N=4 5 6

567

678

P=3x3 logical array


A=7 4 1

852

963

B=9 6 3

852

741
Q=3x3 logical array

000

111

111

V SEMESTER 22 Batch
19
DSP LAB MANUAL

C=7 8 9

456

123

D=1 2 3

456

789

R=3x3 logical array

000

111

111

E=1 2 3

456

789

F=7 8 9

456

123

S=3x3 logical array

000

111

000

V SEMESTER 22 Batch
20
DSP LAB MANUAL

Program 2:

clc;
clear all;
close all;

a=100;

b=200;

if(a>=b)

Max=a;

Else

Max=b;

End

a=100;

b=200;

if(ge(a, b));

Max=a;

Else

Max=b;

End

Output:

Max 200

Max 200

V SEMESTER 22 Batch
21
DSP LAB MANUAL

Program3:
clc;
clear all;
close all;

a=340;

b=520;

if(le(a,b));

Disp(‘a is either less than or equal to b’);

else

disp(‘a is greater than b’);

End

Output:

Max 200

Max 200

a is either less than or equal to b

Result:
Relational operations are performed successfully using MATLAB Commands.

V SEMESTER 22 Batch
22
DSP LAB MANUAL

Experiment 4
Logical Operations
AIM: - To Perform Logical operations using Mat lab.
SOFTWARE REQUIRED: - Mat lab (R2013b)
THEORY:

MATLAB offers two types of logical operators and functions −


• Element-wise − these operators operate on corresponding elements of logical arrays.
• Short-circuit − these operators operate on scalar, logical expressions.
Element-wise logical operators operate element-by-element on logical arrays. The symbols &, |,
and ~ are the logical array operators AND, OR, and NOT.
Short-circuit logical operators allow short-circuiting on logical operations. The symbols && and
|| are the logical short-circuit operators AND and OR.

Functions for Logical Operations


Apart from the above-mentioned logical operators, MATLAB provides the following commands
or functions used for the same purpose −

Sr.No. Function &


Description
1 and(A, B)
Finds logical AND of array or scalar inputs; performs a logical AND of all input arrays
A, B, etc. and returns an array containing elements set to either logical 1 (true) or logical
0 (false). An element of the output array is set to 1 if all input arrays contain a nonzero
element at that same array location. Otherwise, that element is set to 0.

2 not(A)
Finds logical NOT of array or scalar input; performs a logical NOT of input array A and
returnsan array containing elements set to either logical 1 (true) or logical 0 (false). An
element of theoutput array is set to 1 if the input array contains a zero value element at
that same array location. Otherwise, that element is set to 0.

3 or(A, B)
Finds logical OR of array or scalar inputs; performs a logical OR of all input arrays A,
B, etc.and returns an array containing elements set to either logical 1 (true) or logical
0 (false). An

V SEMESTER 22 Batch
23
DSP LAB MANUAL

element of the output array is set to 1 if any input arrays contain a nonzero element at that same
array location. Otherwise, that element is set to 0.

4 xor(A, B)
Logical exclusive-OR; performs an exclusive OR operation on the corresponding elements of
arrays A and B. The resulting element C(i,j,...) is logical true (1) if A(i,j,...) or B(i,j,...), but not
both, is nonzero.
5 all(A)
Determine if all array elements of array A are nonzero or true.
• If A is a vector, all(A) returns logical 1 (true) if all the elements are nonzero and returns
logical 0 (false) if one or more elements are zero.
• If A is a nonempty matrix, all(A) treats the columns of A as vectors, returning a row
vector of logical 1's and 0's.
• If A is an empty 0-by-0 matrix, all(A) returns logical 1 (true).
• If A is a multidimensional array, all(A) acts along the first non-singleton dimension and
returns an array of logical values. The size of this dimension reduces to 1 while the sizes
of all other dimensions remain the same.
6 all(A, dim)
Tests along the dimension of A specified by scalar dim.

7 any(A)
Determine if any array elements are nonzero; tests whether any of the elements along various
dimensions of an array is a nonzero number or is logical 1 (true). The any function ignores
entries that are NaN (Not a Number).
• If A is a vector, any(A) returns logical 1 (true) if any of the elements of A is a nonzero
number or is logical 1 (true), and returns logical 0 (false) if all the elements are zero.
• If A is a nonempty matrix, any(A) treats the columns of A as vectors, returning a row
vector of logical 1's and 0's.
• If A is an empty 0-by-0 matrix, any(A) returns logical 0 (false).
• If A is a multidimensional array, any(A) acts along the first non-singleton dimension and
returns an array of logical values. The size of this dimension reduces to 1 while the sizes
of all other dimensions remain the same.
8 any(A,dim)
Tests along the dimension of A specified by scalar dim.

9 false
Logical 0 (false)

10 false(n)
is an n-by-n matrix of logical zeros

11 false(m, n)
is an m-by-n matrix of logical zeros.

12 false(m, n, p, ...)
is an m-by-n-by-p-by-... array of logical zeros.

V SEMESTER 22 Batch
24
DSP LAB MANUAL

13 false(size(A))
is an array of logical zeros that is the same size as array A.
14 false(...,'like',p)
is an array of logical zeros of the same data type and sparsity as the logical array p.

15 ind = find(X)
Find indices and values of nonzero elements; locates all nonzero elements of array X, and
returns the linear indices of those elements in a vector. If X is a row vector, then the returned
vector is a row vector; otherwise, it returns a column vector. If X contains no nonzero elements
or is an empty array, then an empty array is returned.
16 ind = find(X, k)
ind = find(X, k, 'first')
Returns at most the first k indices corresponding to the nonzero entries of X. k must be a
positive integer, but it can be of any numeric data type.
17 ind = find(X, k, 'last')
returns at most the last k indices corresponding to the nonzero entries of X.

18 [row,col] = find(X, ...)


Returns the row and column indices of the nonzero entries in the matrix X. This syntax is
especially useful when working with sparse matrices. If X is an N-dimensional array with N >
2, col contains linear indices for the columns.
19 [row,col,v] = find(X, ...)
Returns a column or row vector v of the nonzero entries in X, as well as row and column
indices. If X is a logical expression, then v is a logical array. Output v contains the non-zero
elements of the logical array obtained by evaluating the expression X.

20 islogical(A)
Determine if input is logical array; returns true if A is a logical array and false otherwise. It
also returns true if A is an instance of a class that is derived from the logical class.

21 logical(A)
Convert numeric values to logical; returns an array that can be used for logical indexing or
logical tests.
22 true
Logical 1 (true)

23 true(n)
is an n-by-n matrix of logical ones.

24 true(m, n)
is an m-by-n matrix of logical ones.

V SEMESTER 22 Batch
25
DSP LAB MANUAL

25 true(m, n, p, ...)
is an m-by-n-by-p-by-... array of logical ones.

26 true(size(A))
is an array of logical ones that is the same size as array A.

27 true(...,'like', p)
is an array of logical ones of the same data type and sparsity as the logical array p.

Program 1:

clc;
clear all;
close all;

a=[1 0 1 0];

b=[0 1 0 1];

lAND=a&b;

display(lAND);

c=[0 1 0 1];

d=[1 0 1 0];

lOR=a/b;

display(lOR);

e=[1 0 1 0 1 0 1 0];

lNOT=~e;

display(lNOT);

f=[1 1 0 0];

g=[0 0 1 1];

lXOR=xor(f,g);

display(lXOR);

V SEMESTER 22 Batch
26
DSP LAB MANUAL

lXNOR=xnor(f,g);

display(lXNOR);

k=[1 1 1 0];

l=[0 1 0 1];

lNAND=nand(k,l);

display(lNAND);

lNOR=nor(k,l);

display(lNOR);

false(e);

display(false);

true(e);

display(true);

all(a);

display(false);

all(a);

display(true);

Output:

lAND

[ 0 0 0 0]

lOR

[1 1 1 1]

lNOT

[0 1 0 1 0 1 0 1]

V SEMESTER 22 Batch
27
DSP LAB MANUAL

lXOR

[1 1 1 1]

lXNOR

[0 0 0 0]

lNAND

[1 0 1 1]

lNOR

[0 0 0 0]

False

True

False
0
True
1

Result
Logical operations are performed successfully using MATLAB Commands.

V SEMESTER 22 Batch
28
DSP LAB MANUAL

Experiment 5
Testing of input and output variables (numbers and strings)
AIM: - To Perform Testing of input and output variables (numbers and strings) using MATLAB
Commands

SOFTWARE REQUIRED: - Mat lab (R2013b)


THEORY :
Characters and Text

Enter text into MATLAB using single quotes. For example,

>> S = 'Hello'

The result is not the same kind of numeric matrix or array we have been dealingwith up to
now. The string is actually a vector whose components are the numeric codesfor the characters (the
first 127 codes in ASCII). The length of S is the number of characters. It is a 1-by-5-character array.
A quote within the string is indicated by two quotes.

Concatenation with square brackets joins text variables together into larger
strings. For example,
>> h = ['MAT', 'LAB']
joins the strings horizontally and produces
h=
MATLAB
and the statement
>> v = ['MAT'; 'LAB']
joins the strings vertically and produces
v=
M
A
T
L
A
B

Note that both words in v have to have the same length. The resulting arrays
are both character arrays; h is 1-by-6 and v is 2-by-3.

V SEMESTER 22 Batch
29
DSP LAB MANUAL

Some StringFunction

Function Description
char (x) converts the array x that contains positive
>> char(100) integers representing character codes into a
ans = MATLAB character array (the first 127 codes in
d ASCII).
>> char([73 82 65 81])
ans =
IRAQ
double(s) converts the character array to a numeric matrix
>> double('z') ans = containing floating point representations of the
122 ASCII codes for each character.
>> double('ali') ans =
97 108 105

strcat(S1,S2,...) joins S1,S2,...variables horizontally


>>strcat('Hello',' Ali') ans = together into larger string.
Hello Ali
strvcat(S1,S2,...) joins S1,S2,... variables vertically together into
>> strvcat ('Hello', 'Hi', 'Bye') larger string.
ans =
Hello Hi Bye
s = num2str(x) converts the variable x into
>> num2str(20) ans = a string representation s.
20 % as a string,
not a number
x = str2num(s) converts character array representation of a
>> str2num('20') ans = matrix of numbers to a numeric matrix.
20
error (Msg) displays the error message in the string (Msg),
and causes an error exit from the currently
executing M-file to the
keyboard.
lower(A) Converts any uppercase characters in A to the
corresponding lowercase character and
leaves all other characters unchanged.

upper(x) Converts any lower case characters in A to


the corresponding upper case character and
leaves all other characters unchanged

V SEMESTER 22 Batch
30
DSP LAB MANUAL

Note

The printable characters in the basic ASCII character set are represented by the integers
32:127. (The integers less than 32 represent nonprintable control characters). Try
>> char(33:127)

Input of Variable

• To enter matrix or vector or single element:


>> x=input('parameter= ')
parameter= 2
x=
2
>> x=input('parameter= ')
parameter= [2 4 6]
x=2 4 6
>> x=input('parameter= ')
parameter= [1 2 3;4 5 6]
x= 1 2 3

4 5 6

• To enter text:
>> x=input('parameter= ')
parameter= 'faaz'
x= Notice the difference
faaz between the two
statements
>> x=input('parameter= ' , 's' )
parameter= faaz
x= faaz

V SEMESTER 22 Batch
31
SCETW DSP LAB(SPC511EC)

Output of Variable

• disp ( x )

displays the array ( x ), without printing the array name. In all other ways
it's the same as leaving the semicolon off an expression except that empty arrays don't
display.
If ( x ) is a string, the text is displayed.

>> x=[1 2 3];


>> x
x=
1 2 3

>> disp(x)
1 2 3

Example:

>> a=6;
>> b=a;
>> s='Ahmed has ';
>> w='Ali has ';
>> t=' Dinars';
>>disp([ s num2str(a) t]);
>>disp([ w num2str(b) t]);

The execution result is:


Ahmed
has 6
Dinars
Ali has
6 Dinars

Program
%caluculate avg of 3 tests

Test1=iput(‘enter test 1> ‘);

Test2=iput(‘eter test 2> ‘);

V SEMESTER 22 Batch
32
SCETW DSP LAB(SPC511EC)

Test3=input(‘enter test> ‘);

(test1+test2+test3)/3;

Name=input(‘enter your name>’,’s’);

Menu(‘select your course’,’caluculus’,’linear algebra’,’matlab’);

Disp(test1);

Disp(name);

Disp(ans);

Disp([test1 test2 test3]);

Output
Enter test1>87
Test1=87
Eter test2>82
Test2=82
Enter test3>96
Test3=93
Ans=83.33
Enter name
Geetha
Ans
geetha
89
Geetha
70

Result
Testing of input and output variables (numbers and strings) are performed successfullyusing
MATLAB Commands.

V SEMESTER 22 Batch
33
SCETW DSP LAB(SPC511EC)
Experiment 6
Flow Control Functions
AIM: - To Perform Flow control functions using Mat lab.
SOFTWARE REQUIRED: - Mat lab (R2013b)
THEORY :
A control flow subsystem executes one or more times at the current time step when enabled
by a control flow block. A control flow block implements control logic similar to that
expressed by control flow statements of programming languages (e.g., if-then, while-
do, switch, and for).
Equivalent C Language Statements
You can use block diagrams to model control flow logic equivalent to the following C
programming language statements:
• for
• if-else
• switch
• while
Conditional Control Flow Logic
You can use the following blocks to perform conditional control flow logic.

C Statement Equivalent Blocks

if-else If, If Action Subsystem


Switch Switch Case, Switch Case Action Subsystem
While and For Loops
Use the following blocks to perform while and for loops.

C Statement Equivalent Blocks

do-while While Iterator Subsystem


For For Iterator Subsystem
While While Iterator Subsystem
The MATLAB code has its own instructions for flow of control statements like 'for-loops',
'while' and 'if-elseif' branching. See details and examples...
Among the control structures in programming languages, there is the while... end loop which
repeats a group of statements an indefinite number of times under control of a logical condition.

Syntax:
while expression
statements
Theifcautions
end
the statement
involving
also apply
matrix
to the
comparisons
while statement.
that a

V SEMESTER 22 Batch
34
SCETW DSP LAB(SPC511EC)

An end keyword, which matches the if, terminates the last group of statements.This type of structure is
also known as branches or 'branching'.
The groups of statements are delineated by the four keywords (no braces orrackets are involved).

The general form of the statement is:

if expression1
statements1
...
elseif expression2
statements2
...
else
statements3
...

end

It is important to understand how relational operators and if statements work with matrices.

When you want to check for equality between two variables, you might use if A == B ...

This '==' code is fine, and it does what you expect when A and B are scalars.

But when A and B are matrices, A == B does not test if they are equal, it tests where they are
equal; the result is another matrix of 0’s and 1’s showing element-by-element equality.

In fact, if A and B are not the same size, then A == B is an error.


The proper way to check for equality between two variables is to use the isequal function:

if isequal(A,B) ...

Several functions are helpful for reducing the results of matrix comparisons to scalarconditions for use
with if, including:
V SEMESTER 22 Batch
35
SCETW DSP LAB(SPC511EC)

isequal
isempty
all
any

Program
clc;
clear all;
close all;

c = 5;
% Pre allocate matrix, fill it with zeros
a = zeros(c, c);
for m = 1 : c
for n = 1 : c
a(m, n) = 1/(m + n * 5);
end
end
counter = 100;
while (counter > 95)
disp ('counter is still > 95')
counter = counter -1;
end
disp('counter is no longer > 95')
if m == n
a(m,n) = 3;
elseif abs(m-n) == 3
a(m,n) = 1;
else
a(m,n) = 0;
end

Output:
If m equals n, then a(m,n) becomes 3, and the routine continues after the end.
If not, the routine tests if abs(m-n) equals 3. If it does, then a(m,n) becomes 1, and the routine continues
after the end.
In any other case a(m,n) becomes 0, and the routine continues after the end.

Result:
Flow control functions are performed successfully using MATLAB Commands.

V SEMESTER 22 Batch
36
SCETW DSP LAB(SPC511EC)

Experiment 7
Complex and Statistical Functions

AIM:- To Perform Complex and Statistical Functions using MATLAB Commands.

SOFTWARE REQUIRED: - Mat lab (R2013b)


THEORY:
Complex Numbers are the combination of real numbers and imaginary numbers in the form of p+qi where

p and q are the real numbers and i is the imaginary number. An imaginary number is defined where i is

the result of an equation a^2=-1. We can use i or j to denote the imaginary units. As complex numbers

are used in any mathematical calculations and Matlab is mainly used to perform mathematical

calculations. So, complex numbers form an important part of learning Matlab.

Complex Numbers Generation in MATLAB:


Complex Numbers can be created or declared in Matlab using a ‘complex’ function. We can also

create complex numbers by finding the square root of any negative number. In Matlab, we can

use i or j to denote the imaginary part of the complex number.

Complex Numbers
Real and imaginary components, phase angles

In MATLAB®, i and j represent the basic imaginary unit. You can use them to create complex
numbers such as 2i+5. You can also determine the real and imaginary parts of complex numbers
and compute other common values such as phase and angle.
Functions

abs Absolute value and complex magnitude

angle Phase angle

complex Create complex array

conj Complex conjugate

cplxpair Sort complex numbers into complex conjugate pairs

V SEMESTER 22 Batch
37
SCETW DSP LAB(SPC511EC)

i Imaginary unit

imag Imaginary part of complex number

isreal Determine whether array uses complex storage

j Imaginary unit

real Real part of complex number

sign Sign function (signum function)

unwrap Shift phase angles

Functions for Calculating Descriptive Statistics


Use the following MATLAB® functions to calculate the descriptive statistics for your data.
Note
For matrix data, descriptive statistics for each column are calculated independently.

Statistics Function Summary

Function Description
max Maximum value
mean Average or mean value
median Median value
min Smallest value
mode Most frequent value
std Standard deviation
var Variance, which measures the spread or dispersion of the values

Example 1 — Calculating Maximum, Mean, and Standard Deviation


This example shows how to use MATLAB functions to calculate the maximum, mean, and
standard deviation values for a 24-by-3 matrix called count. MATLAB computes these statistics
independently for each column in the matrix.
% Load the sample data
load count.dat
% Find the maximum value in each column
mx = max(count)
% Calculate the mean of each column
mu = mean(count)
V SEMESTER 22 Batch
38
SCETW DSP LAB(SPC511EC)
% Calculate the standard deviation of each column
sigma = std(count)

The results are


mx =
114 145 257

mu =
32.0000 46.5417 65.5833

sigma =
25.3703 41.4057 68.0281
To get the row numbers where the maximum data values occur in each data column, specify a second
output parameter index to return the row index. For example:
[mx,indx] = max(count)
These results are
mx =
114 145 257

indx =
20 20 20
Here, the variable mx is a row vector that contains the maximum value in each of the three datacolumns.
The variable indx contains the row indices in each column that correspond to the maximum values.
To find the minimum value in the entire count matrix, 24-by-3 matrix into a 72-by-1 column vector by
using the syntax count(:). Then, to find the minimum value in the single column, usethe following
syntax:
min(count(:))

ans = 7

PROGRAM
clc;
clear all;
close all;
t=0:0.1:4;

V SEMESTER 22 Batch
39
SCETW DSP LAB(SPC511EC)
f=(1+0.25*i).*t-2.0;
amp=abs(f);
p=rad2deg(angle(f));
subplot(2,1,2);
plot(t,amp);
title(‘amplitude’);
xlabel(‘time’);
ylabel(‘amplitude’);
subplot(2,1,2);
plot(t,p);
title(‘phase plot of a complex’);
xlabel(‘time’);
ylabel(‘phase’);
%statistical function

Program
V1=[10,11,13,15,23];
V2=[10,11,13,15];
V3=[10,15,23,11,13];
Mean(x)=avg of a vector
V1_mean=mean(v1);
Std(x)=standard deviation of a vector
V1_std=std(v1);
V1_min=min(v1);
V3_min=min(v3);
[v1_min,idx_min]=min(v1);
V1_max=max(v1);
V3_max=max(v3);
[v1_max,idx_max]=max(v1);

V SEMESTER 22 Batch
40
SCETW DSP LAB(SPC511EC)
Output
V1_min=10
Idx_min=1
V1_max=23
Idx_max=5

Result
Complex and statistical functions are performed successfully using MATLAB Commands.

V SEMESTER 22 Batch
41
SCETW DSP LAB(SPC511EC)

Experiment 8
2D plotting
AIM: - To Perform 2D plotting using Mat lab.
SOFTWARE REQUIRED: - Mat lab (R2019b)
THEORY:
MATLAB supports more types of two-dimensional (2D) plots. We are trying to coverplots
which are widely used in industry and in different projects.

Here is a list of 10 various MATLAB 2D plots.


1. Area Plot
2. Bar Plot
3. Stem Plot
4. Stairs Plot
5. Barh Plot
6. Pie Plot
7. Polar Plot
8. Compass Plot
9. Scatter Plot
10. Errorbar Plot
Now, I am describing each 2D plots by using the MATLAB code and its decorating
functions in details.

1. Area Plot
In the Area plotting graph, Area. you can use basic functions. It is a very easy draw.

In the MATLAB plotting, there is a function area () to plot

The syntax for the Area plot…


Area (x)

2. Stem Plot
In Stem plot, the discrete sequence data and variables are used. This plot is created by
using the stem () function.

Syntax: The syntax for the stem plot is,


stem(x) stem(x,y)
stem(-- ,'colour')
stem(-- ,'width')
stem(-- ,'style')

V SEMESTER 22 Batch
42
SCETW DSP LAB(SPC511EC)

3. Bar Plot
You can create different types of bar plot in MATLAB. Here, I am explaining the simple
bar plot code with the help of multiple functions.

Syntax: The syntax for the bar plot is,


bar(x,y)
bar(x,y,'colourmarkerlinespec')

4.Pie Plot
In mathematics, the pie chart is used to indicate data in percentage (%) form.

In MATLAB, you can draw different kinds of pie plots by using simple code.

Syntax: The syntax for the pie plot is,

pie(x)

5. Stairs Plot
This is again one of the MATLAB 2D plots that look more like stairs.

Syntax: The syntax for the stair plot is,


Stairs (x,y)
stair (x,y,'colourmarkerlinspec')

Program:
% To create the area plot for the given equation Sin(t)Cos(2t).
% Enter the value of range of variable 't'.

t=[0:0.2:20];

% Put the given equation

a=[sin(t).*cos(2.*t)];

area(a)

title('Area Plot')

% Consisder the variable range of 'x' and 'y',

x=[3 1 6 7 10 9 11 13 15 17];

V SEMESTER 22 Batch
43
SCETW DSP LAB(SPC511EC)
y=[14 7 23 11 8 16 9 3 23 17];

stem(x,y,'r')

title('Stem Plot')

xlabel('X axis')

ylabel('Y axis')

x=[1 3 5 7 10 13 15];

y=[0 0.5 1 1.5 3 2 2];

bar(x,y)

title('Bar Plot')

xlabel('X axis')

ylabel ('y axis')

x=[1 3 5 7 10 13 15];

y=[0 0.5 1 1.5 3 2 2];

barh (x,y)

title('Barh Plot')

xlabel('X axis')

ylabel('y axis')

x=[10 20 25 40 75 80 90];

pie(x)

title('Pie Plot')

x=[0 1 2 4 5 7 8];

y=[1 3 4 6 8 12 13];

V SEMESTER 22 Batch
44
SCETW DSP LAB(SPC511EC)
stairs(x,y,'k');

title('Stairs Plot')

xlabel('X axis')

ylabel('Y axis')

Output:

V SEMESTER 22 Batch
45
SCETW DSP LAB(SPC511EC)

Result
2D PLOTTING is performed successfully using MATLAB Commands

V SEMESTER 22 Batch
46
SCETW DSP LAB(SPC511EC)

Experiment 9
3D plotting

AIM: - To Perform 3D plotting using Mat lab.


SOFTWARE REQUIRED: - Mat lab (R2013b)
THEORY:

In general, the three-dimensional plots consist of the three vectors (x,y,z) in the same graph. In
MATLAB, the plot3() function is used to draw the 3D plot graph. You can also use a specified
line style, marker, and color for drawing 3D plots.

The general syntax to display the 3D plot is,

plot3(x,y,z)

plot3(x,y,z,Name)

plot3(x,y,z,LineSpec)

Let’s start drawing different types of the 3D plot graph…

Classifications of Three-Dimensional Plots | MATLAB 3D plot Examples

Here, we are considering, the five main different types of three-dimensional (3D) plots. These
graphs are mostly used in the industry.

The following list of different 3D plots as,


1. Mesh Plot
2. Surface Plot
3. Ribbon PLot
4. Contour Plot
5. Slice Plot
As a part of this tutorial about MATLAB 3D plot examples, I am describing the topmost five 3D
plots one-by-one.

1. Mesh 3D Plot in MATLAB

The mesh plotting function is used to display the mesh plot. It produces a wireframe surface
where the lines connecting the defining points are colored.
How to create the Mesh plot in MATLAB?
For the mesh plotting in MATLAB, you need to pass the array values to the mesh function.

V SEMESTER 22 Batch
47
SCETW DSP LAB(SPC511EC)

Syntax:
Mesh function transforms the domain specified by vectors (X, Y, Z) into arrays (x,y,z).

The syntax for the Mesh Plot is,

mesh(x,y,z)

[X,Y,Z] = meshgrid(x,y,z)

2. Surface 3D Plot in MATLAB


A surface plot is somewhat similar to a mesh plot. The main difference between them is, in the
surface plot, the connecting lines and the faces both will be displayed in the dark color.
How to create the Surf plot in MATLAB?
Syntax:
In the surface plot, ‘surf’ function is used. So, you can write a simple format like ‘function
name(array)’.

surf(x,y,z)

surf(z)

Ribbon 3D Plot in MATLAB

As the name ribbon, this 3D plot graph will be having different color ribbons.
How to create the ribbon plot in MATLAB?
Here, we are using ribbon() function for plotting ribbon 3D MATLAB plot.

Syntax:
The general syntax for writing code,
ribbon(x,y,z)
ribbon(x,y)
ribbon(z)

4. Contour 3D Plot in MATLAB

How to create the three dimensional [3D] contour plot?


To create the three dimensional [3D] contour plot, we are using the ‘contour3’ function.

Note: You can plot the Contour 2D plot by using the only ‘contour’ function.

Syntax:
The syntax for the three-dimensional contour
plot,contour3(x,y,z)
contour3(z)

V SEMESTER 22 Batch
48
SCETW DSP LAB(SPC511EC)

5. Slice 3D Plot in MATLAB

For plotting slice graph, you must know volumetric data(v), specification of three-dimensional
coordinate (x,y,z), and ‘xslice, yslice, zslice’.

Syntax:

Slice plot’s syntax is


slice(x,y,z,v,xslice,yslice,zslice)
slice(v,xslice,yslice,zslice)
Where,
• xslice- ‘x’ coordinate data for slice plot
• yslice- ‘y’ coordinate data for slice plot
• zslice- ‘z’ coordinate data for slice plot

Program
clc;
clear all;
close all;

[x,y] = meshgrid(-10:0.1:10);

t = sqrt(x.^2+y.^2);

z =(10*sin(t));

mesh(x,y,z)

[x,y] = peaks(30);

z = exp(-0.9*(x.^2+0.5*(x-y).^2));

surf(x,y,z);

xlabel('\bf X axis');

ylabel('\bf Y axis');

zlabel('\bf Z axis');

title('\bf Surface Plot')

V SEMESTER 22 Batch
49
SCETW DSP LAB(SPC511EC)

colorbar

[x,y] = peaks(30);

z =[(x.^2)-(y.^2)];

ribbon(z);

title('\bf Ribbon Plot')

[x,y] = peaks(30);

z = exp(-x.^2-y.^2);

contour3(x,y,z);

title('\bf Contour Plot')

[x,y,z] = meshgrid(-10:.2:10);

v = [exp((x.^2)-(y.^3)-(z.^5))];

xslice = 0.1;

yslice = 5;

zslice = 0;

slice(x,y,z,v,xslice,yslice,zslice)

colorbar

title('\bf Slice Plot')

V SEMESTER 22 Batch
50
SCETW DSP LAB(SPC511EC)
OUTPUT

V SEMESTER 22 Batch
51
SCETW DSP LAB(SPC511EC)

V SEMESTER 22 Batch
52
SCETW DSP LAB(SPC511EC)

RESULT
3D PLOTTING is performed successfully using MATLAB Commands

V SEMESTER 22 Batch
53

You might also like