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

Lab_1

This document serves as an introduction to MATLAB, focusing on its basic functionalities for signal representation, visualization, and processing. It covers arithmetic operations, display formats, built-in math functions, variable management, and array manipulation. The lab aims to equip students with the skills to effectively use MATLAB in signal processing tasks.
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)
10 views19 pages

Lab_1

This document serves as an introduction to MATLAB, focusing on its basic functionalities for signal representation, visualization, and processing. It covers arithmetic operations, display formats, built-in math functions, variable management, and array manipulation. The lab aims to equip students with the skills to effectively use MATLAB in signal processing tasks.
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/ 19

LAB 1 : MATLAB INTRODUCTION

CLO5: USE MODERN TOOL (E.G. MATLAB) FOR SIGNAL REPRESENTATION , VISUALIZATION AND
PROCESSING IN BOTH TIME AND FREQUENCY DOMAIN .

Objective:
Most of the Lab work will be covered using MATLAB. The main objective of this lab manual is to
introduce the basics of MATLAB.

SECTION-A
1. Arithmetic Operations:
All basic arithmetic operations can be performed using MATLAB. The symbols are listed in table
below:

Arithmetic Operation Symbol Example


Addition + 6+3=9
Subtraction – 6–3=3
Multiplication * 6 * 3 = 18
Right Division / 6/3=2
Left Division \ 6 \ 3 = 0.5
Exponentiation ^ 6 ^ 3 = 216

2. Display Formats:
MATLAB has several screen display formats for displaying numbers. They are listed below. You
can try them in command window like >>format short and the format will be changed to short.

Command Description Example


format short Fixed-point with 4 decimal digits >> 351/7
ans = 50.1429
format long Fixed-point with 14 decimal digits >> 351/7
ans = 50.14285714285715
format short e Scientific notation with 4 decimal digits >> 351/7
ans = 5.0143e+001
format long e Scientific notation with 15 decimal digits >> 351/7
ans = 5.014285714285715e0001
format short g Best of 5 digit fixed or floating point >> 351/7
ans = 50.143
format long g Best of 15 digit fixed or floating point >> 351/7
ans = 50.1428571428571
format bank Two decimal digits >> 351/7
ans = 50.14

Test Yourself

MCT-244L: Signal Processing


Department of Mechatronics and Control Engineering, U.E.T Lahore
There are two formats known as format compact and format loose. Search on MATLAB about
these formats using help or doc command and write down the difference between them in your
own words:

3. Elementary Math Built-in Functions:


Some built-in Math functions are listed below:
Common Math Functions

Function Description
abs(x) Computes the absolute value of x
sqrt(x) Computes the square root of x
round(x) Rounds x to the nearest integer
fix(x) Rounds (or truncate) x to the nearest integer 0
floor(x) Rounds x to the nearest integer toward –
ceil(x) Rounds x to the nearest integer toward +
sign(x) Returns a value of –1 if x is less than 0, a value of 0 if x equals 0 and a value of 1
otherwise
rem(x, y) Returns the remainder of x/y. This function is also called modulus function.
exp(x) Computes ex, where e is the base for natural logarithms (or approximately 2.718282)
log(x) Computes ln x, the natural logarithm of x to the base e
log10(x) Computes log10 x, the common logarithm of x to the base 10
log2(x) Computes log2 x, the logarithm of x to the base 2

Trigonometric Functions

Function Description
sin(x) Computes the sine of x, where x is in radians
cos(x) Computes the cosine of x, where x is in radians
tan(x) Computes the tangent of x, where x is in radians
asin(x) Computes the arc-sine or inverse sine of x, where x must be between –1 and 1. The
function returns and angle in radian between –π/2 and π/2
acos(x) Computes the arc-cosine or inverse cosine of x, where x must be between –1 and
1. The function returns and angle in radian between 0 and π

MCT-244L: Signal Processing


Department of Mechatronics and Control Engineering, U.E.T Lahore
atan(x) Computes the arc-tangent or inverse tangent of x, where x must be between –∞
and ∞. The function returns and angle in radian between –π/2 and π/2
atan2(y, x) Computes the arc-tangent or inverse tangent of the value y/x. The function returns
an angle in radian that will be between –π and π, depending on the signs of x and y

Complex Number Functions

Function Description
conj(x) Computes the complex conjugate of the complex number x. thus if x is equal to a
+ ib, then conj(x) will be equal to a – ib
real(x) Computes the real part of the complex number x
imag(x) Computes the imaginary part of the complex number x
abs(x) Computes the absolute value of magnitude of the complex number x
angle(x) Computes the angle using the value of atan2(imag(x), real(x)); thus the angle
value is between –π and π

4. Variable names:
Variable names are case sensitive in MATLAB. So xy, Xy, xY and XY are four different variable
names. Names of built-in functions should not be used as variable name e.g. sin, abs, ceil etc. Also
predefined variable (Mentioned below) names cannot be used for your own variable.

5. Predefined Variables:
Many variables are pre-defined in MATLAB. Some are listed below:
Predefined variables Description
in MATLAB

ans Represents a value computed by an expression but not stored in variable


name

pi Represents the number π


eps Represents the floating-pint precision for the computer being used. This is the
smallest difference between two numbers

inf Represents infinity which for instance occurs as a result of a division by zero.
A warning message will be displayed or the value will be printed as ∞

i Defined as √−1, which is 0 + 1.0000i


J Same as i
NaN Stands for Not a Number. Typically occurs as a result of an expression being
undefined, as in the case of division of zero by zero

clock Represents the current time in a six-element row vector containing year,
month, day, hour, minute and seconds

MCT-244L: Signal Processing


Department of Mechatronics and Control Engineering, U.E.T Lahore
date Represents the current date in a character string format

MCT-244L: Signal Processing


Department of Mechatronics and Control Engineering, U.E.T Lahore
6. Commands for Managing Variables:
Below are some useful commands to manage variables:
Command Description
clear Removes all variables from the memory
clear x, y, z Clears/removes only variables x, y and z from the memory
who Lists the variables currently in the workspace
whos Displays a list of the variables currently in the memory and their size
together with information about their bytes and class

Test Yourself
17(√5−1) 57 log10 (𝑒 3 )
Evaluate + + (ln(4))3 using single line MATLAB statement:
152 −132 𝜋√120

MATLAB Statement Output

7. General Commands:
Following tables give some general commands that can be required many times:
Online – Help

Function Description
help Lists topics on which help is available
helpwin Opens the interactive help window
helpdesk Opens the web browser based help facility
help topic Provides help on topic
lookfor string Lists help topics containing string
demo Runs the demo program
Workspace Information

Function Description
who Lists variables currently in the workspace
whos Lists variables currently in the workspace with their size
what Lists .m, .mat and .mex files on the disk
clear Clears the workspace, all the variables are removed
clear x, y, z Clears only variables x, y and z
clear all Clears all variables and functions from workspace

MCT-244L: Signal Processing


Department of Mechatronics and Control Engineering, U.E.T Lahore
clc Clears command window, command history is lost
clf Clear figure window

8. Arrays:
An array is a list of numbers arranged in rows and/or columns. A one-dimensional array is a
row or a column of numbers and a two-dimensional array has a set of numbers arranged in rows
and columns. An array operation is performed element-by-element. In a row vector the elements
are entered with a space or a comma between the elements inside the square brackets. For
example,
>>x = [7 – 1 2 – 5 8]
In a column vector the elements are entered with a semicolon between the elements inside
the square brackets. For example,
7
−1
>>y = [7 ; – 1 ; 2 ; – 5 ; 8] will generate a column vector y = 2
−5
[ 8]
On the other hand, a row vector is converted to a column vector using the transpose operator.
The transpose operation is denoted by an apostrophe or a single quote (').
7
−1
>>y=x’ will generate the same column vector y = 2
−5
[ 8]
MATLAB also provides shortcuts for elements entry. For example if you want to create a vector v
as:
v= [1 2 3 4 5 6 7 8 9 10]
then instead of writing all numbers from 1 to 10, you can use colon (:) operator like:
>>v = [1:10]
What if you want to enter all odd numbers from 1 to 99 in a vector w? You can use colon operator
as:
>>w=[1:2:99];
The first value i.e. 1 is that starting value, then 2 is the amount of increment and 99 is the last
value of the vector.

Test Yourself
Define a vector z=[1000 997 994 991 … 100]

MCT-244L: Signal Processing


Department of Mechatronics and Control Engineering, U.E.T Lahore
Note: Once you have written the command to produce above vector, change 100 to 99 and see
the output.

Accessing elements of a vector:


We can access any element of a vector e.g. for the vector x = [7 – 1 2 – 5 8]; x(1) is the first
element, x(2) is the second and so on. So
>>a=x(4) ; % will assign -5 to a.
We can also access block of elements. For example:
>>b=x(2:5); % will make b=[– 1 2 – 5 8]
The keyword end specifies the index last element of the array. For example z(end) will give the
last element of the array z and z(10:end) will gives all element from 10th to the last.

2-D array or Matrix:


A matrix is a two-dimensional array which has elements in rows and columns. A matrix is entered
row-wise with consecutive elements of a row separated by a space or a comma, and the rows
separated by semicolons. The entire matrix is enclosed within square brackets. The elements of
the matrix may be real numbers or complex numbers. For example to enter the matrix:
1 3 −4
x=[ ] Command will be:
0 −2 8
>>x=[1 3 -4;0 -2 8];
Accessing the elements of Arrays:
Any element or set of elements can be accessed by specifying its row and column.
Command Description
A(m, n) Refers to single element of row m and column n
A(:, n) Refers to the elements in all the rows of a column n of the matrix A
A(n, :) Refers to the elements in all the columns of row n of the matrix A
A(:, m:n) Refers to the elements in all the rows between columns m and n of the matrix A
A(m:n, :) Refers to the elements in all the columns between rows m and n of the matrix A
A(m:n, p:q) Refers to the elements in rows m through n and columns p through q of the matrix
A

Editing/Adding/Removing elements:
Element(s) of matrix can be changed by accessing them like

MCT-244L: Signal Processing


Department of Mechatronics and Control Engineering, U.E.T Lahore
>>A (2, 3) =7; will change element of second row and third column to 7.
You can always add elements to the existing matrix. For example, in matrix x defined above as
>>x=[1 3 -4;0 -2 8];
5
It has two rows and three columns and if you want to add fourth column as [ ] within same matrix
6
x, it can be done as:
>> x=[x [5;6]];
What about adding another row; the third one e.g. [ 4 4 4 4] in updated matrix x?
It will be done as:
>> x=[x ; [4 4 4 4]]; % See carefully where we need a space and where a semicolon!!
Similarly element(s) of matrix can be deleted by referring them to empty square brackets like:
>>A (2, : )= []; will delete all elements of row 2.
Note: By above command of deleting the element(s) size of the matrix will be changed so it’s
obvious that you can only delete entire row or column. For example in a 3x3 matrix you cannot
delete element (2,2) only or (2,3) only or (2,1) only etc.

Test Yourself
Without using MATLAB find out the elements of matrix e:
>>a=[5 3];
>>b=[a;a];
>>c=[4;6];
>>d=[8 9 7 1];
>>e=[b c c; d]
Verify the output by executing the code on MATLAB.
Once you get the matrix e, write MATLAB command to delete the 3rd column.
MATLAB Statement Output

MATLAB provides functions that generates elementary matrices. The matrix of zeros, the matrix of
ones, and the identity matrix are returned by the functions zeros, ones, and eye, respectively.

MCT-244L: Signal Processing


Department of Mechatronics and Control Engineering, U.E.T Lahore
Function Description
eye(n) Returns an n-by-n square identity matrix
zeros(n) Returns an n-by-n square matrix of zeros
zeros(m,n) Returns an m-by-n matrix of zeros
ones(n) Returns an n-by-n square matrix of ones
ones(m,n) Returns an m-by-n matrix of ones
rand(n) Returns an n-by-n square matrix of random values (b/w 0 and 1)
rand(m,n) Returns an m-by-n matrix of random values (b/w 0 and 1)
randi(i) Returns one random integer between 1 and i.
randi(i,n) Returns an n-by-n square matrix of random integers (b/w 1 and i)
randi(i,m,n) Returns an m-by-n matrix of random integers (b/w 1 and i)

Some built-in functions for arrays:


Function Description Example
length(A) Returns the number of elements in the >> A = [5, 9, 2, 4];
vector A >> length(A)
ans = 4
size (A) Returns a row vector [m, n], where m >> A = [2, 3, 0, 8, 11; 6, 17, 5, 7, 1]
and n are the size m x n of the array A A =
2 3 0 8 11
6 17 5 7 1
>> size(A)
ans = 2 5
reshape (A, m, n) Rearrange a matrix A that has r rows >> A = [3 1 4; 9 0 7]
and s columns to have m rows and n A =
columns. r times s must be equal to m 3 1 4
times n 9 0 7
>> B = reshape(A, 3, 2)
B=
3 0
9 4
1 7
diag (v) When v is a vector, creates a square >> v = [3 2 1];
matrix with the elements of v in the >> A = diag(v)
diagonal A=
3 0 0
0 2 0
0 0 1
diag(A) When A is a matrix, creates a vector
from the diagonal elements of A >> A = [1 8 3; 4 2 6; 7 8 3]
A=
1 8 3
4 2 6
7 8 3
>> vec = diag(A)
vec =

MCT-244L: Signal Processing


Department of Mechatronics and Control Engineering, U.E.T Lahore
1
2
3

Test Yourself
Without using MATLAB, write down the output of following commands:
>> a = [1 2 3 ;4 5 6 ;7 8 9] ;
>> b = [a, zeros (3,2); ones(2,3),eye(2)]

Test Yourself
Enter following matrix in MATLAB:
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
𝐴 = 17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
[33 34 35 36 37 38 39 40]
Create a 3 × 4 matrix B from the 1st , 3rd , and the 5th rows, and the 1st , 2nd , 4th , and 8th columns
of the matrix A.
MATLAB Statement Output

MCT-244L: Signal Processing


Department of Mechatronics and Control Engineering, U.E.T Lahore
Operations with Arrays:
Arithmetic operation can be performed using arithmetic operation symbols. Important thing is
that Matrix operations are performs by arithmetic symbols like +, -, * etc and element -by-element
operation (Also known as Array Operations) are perform by a “.” Before the symbol like .*, .^ etc

Matrix Operations Array Operations


+ Addition + Addition
– Subtraction – Subtraction
* Multiplication .* Array multiplication
^ Exponentiation .^ Array exponentiation
/ Left division ./ Array left division
\ Right division .\ Array right division

Some more built-in functions for arrays are listed below:


Function Description Example
mean (A) If A is a vector, returns the mean value of >> A = [3 7 2 16];
the elements >> mean(A)
ans = 14
C = max (A) If A is a vector, C is the largest element in >> A = [3 7 2 16 9 5 18 13 0 4];
A. If A is a matrix, C is a row vector >> C = max(A)
containing the largest element of each C = 18
column of A
[d, n] = max (A) If A is a vector, d is the largest element in >> A = [3 7 2 16 9 5 18 13 0 4];
A, n is the position of the element (the >> [d, n] = max (A)
first if several have the max value) d = 18
n=7
C = min (A) The same as max (A) but for the smallest >> A = [3 7 2 16 9 5 18 13 0 4];
element >> C = min(A)
C=0
[d, n] = min (A) Same as [d, n] = max (A), but for the >> A = [3 7 2 16 9 5 18 13 0 4];
smallest element >> [d, n] = min (A)
d=0
n=9

Function Description Example


sort (A) If A is a vector, arranges the elements of the vector in >> A = [3 7 2 16];
ascending order >> sort (A)
ans = 2 3 7 16
median (A) If A is a vector, returns the median value of the elements >> A = [3 7 2 16];
of the vector >> median (A)
ans = 5
std (A) If A is a vector, returns the standard deviation of the >> A = [3 7 2 16];
elements of the vector >> std (A)
ans = 6.3770
det (A) Returns the determinant of a square matrix A >> A = [3 7 2 16];
>> det (A)

MCT-244L: Signal Processing


Department of Mechatronics and Control Engineering, U.E.T Lahore
ans = –2
dot (a, b) Calculates the scalar (dot) product of two vectors a and b. >> a = [5 6 7];
the vector can each be row or column vectors >> b = [4 3 2 ];
>> dot (a, b)
ans = 52
cross (a, b) Calculates the cross product of two vectors a and b (a x b). >> a = [5 6 7];
The two vectors must have 3 elements >> b = [4 3 2 ];
>> cross (a, b)
ans = –9 18 –9
inv (A) Returns the inverse of a square matrix A >> A = [1 2 3; 4 6 8; –1 2 3];
>> inv (A)
ans =
–0.5000 0.0000 –0.5000
–5.0000 1.5000 1.0000
3.5000 –1.0000 –0.5000
sum (A) If A is a vector, returns the sum of the elements of the >> A = [3 7 2 16];
vector >> sum (A)
ans = 28

Test Yourself
Define following Matrices in MATLAB
2 1 2 3
5 3
A = [0 5] B = [ ] C = [ −5 −2 ] D = [1 2]
−2 −4
7 4 0 3
Compute following matrices and determine if they exist:
a) (ACT )−1 b) |B| c) |ACT |

MATLAB Statement Output

MCT-244L: Signal Processing


Department of Mechatronics and Control Engineering, U.E.T Lahore
Test Yourself
Determine the values of x, y, and z (using Matrices) for the following set of linear algebraic equations:
2x + y – 3z = 11 4x – 2y + 3z = 8 – 2x + 2y – z = – 6

Script M-File:
It consists of sequence of normal MATLAB statements written in a file with extension .m and saved
in MATLAB Directory. If file is saved with name test.m then executing the following command on
main Command Window:
>>test
It will execute instructions in that file one by one. Any variable defined in script file are global which
means that they can be accessed by Command Window.
Function M-File:
You can create new function according to your problem using Function M-File. Variables defined in
Function M-File are local. So they will not be defined in command window. You can create one
function in one Function M-File, however you can use as many existing (built-in or made by yourself)
function as you wish. M-File name should be function name. Function M-File’s first line defines
function name and input/output variables, for example for two input and two output function it is:
function [output_1 output_2] = name(input_1, input_2)

For example if you want to make a very simple function that converts radians to degree, M-file will
be:
function d=r2d(r) %%r2d is name of function, r is input, d is
output
d=r*180/pi

In command window you will use it like:

>>r2d(pi)
ans = 180

Test Yourself
Make a function file with name tri which will take three inputs a, b and c as sides of triangle and will
return its area A and Perimeter P. Show output for some set of sides.
P
P=a+b+c s= A = √s(s − a)(s − b)(s − c)
2

MCT-244L: Signal Processing


Department of Mechatronics and Control Engineering, U.E.T Lahore
M-File Commands Output

MCT-244L: Signal Processing


Department of Mechatronics and Control Engineering, U.E.T Lahore
SECTION-B

1. Programming in MATLAB:
Programming can also be done using MATLAB as in other programming languages. Basic
operators used in programming are:
Relational Operators
Relational Operator Interpretation
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
~= Not equal to

Logical Operators

Logical Operator Name Description


& AND Operates on two operands (A and B). If both are true, the result is
Example: A & B true (1) otherwise the result is false (0)
| OR Operates on two operands (A and B). If either one of both are true,
Example: A | B the result is true (1) otherwise (both are false) the result is false (0)
~ NOT Operates on one operand (A). Gives the opposite of the operand.
Example: ~ A True (1) if the operand is false and false (0) if the operand is true

The order of precedence used by MATLAB is listed below:


Precedence Operation
1 (highest) Parentheses (If nested parentheses exist, inner have precedence)
2 Exponentiation
3 Logical NOT (~)
4 Multiplication, Division
5 Addition, Subtraction
6 Relational operators (>, <, >=, <=, = =, ~=)
7 Logical AND (&)
8 (lowest) Logical OR (|)

Built-in Logical Functions:


MATLAB functions to perform logical operations are:
and(A, B) →Equivalent to A & B
or(A, B) →Equivalent to A | B
not(A) →Equivalent to ~ A

MCT-244L: Signal Processing


Department of Mechatronics and Control Engineering, U.E.T Lahore
Addition Logical Built-in functions are:

Function Description Example


xor (a, b) Exclusive OR. Returns true (1) if one operand is >> xor (8, –1)
true and the other is false ans = 0
>> xor (8, 0)
ans = 1
all (A) Returns true (1) if all elements in a vector A are >> A = [5 3 11 7 8 15];
true (non-zero). Returns false (0) if one or more >> all (A)
elements are false (0). If A is a matrix, treats ans = 1
columns of A as vectors, return a vector with 1’s >> B = [3 6 11 4 0 13];
and 0’s >> all (B)
ans = 0
any (A) Returns true (1) if any element in a vector A is >> A = [5 0 14 0 0 13];
non-zero (true). Returns false (0) if all elements >> any (A)
are zero (false). If A is a matrix, treats columns of ans = 1
A as vectors, returns a vector with 1’s and 0’s >> B = [0 0 0 0 0 0];
>> any (B)
ans = 0
find (A) If A is a vector, returns the indices of the non-zero >> A = [0 7 4 2 8 0 0 3 9];
find (A > d) elements. If A is a vector, returns the address of >> find (A)
the elements that are larger than d (any relational ans = 2 3 4 5 8 9
operator can be used) >> find (A > 4)
ans = 2 5 9
isempty (A) Returns true (1) if A is empty and false (0) >> A = [];
otherwise >> isempty (A)
ans = 1
>> A = [1 0];
>> isempty (A)
ans = 0

Control Flow:
To control the flow of command in MATLAB , you can use
for loops
while loops
if-else-end constructions
switch-case constructions
If-else-end constructions:
Syntax of simple if condition is:

MCT-244L: Signal Processing


Department of Mechatronics and Control Engineering, U.E.T Lahore
if expression
commands
end

This construction is used if there is one alternative only. Two alternatives require the construction
if expression
commands (evaluated if expression is true)
else
commands (evaluated if expression is false)
end

If there are several alternatives one should use the following construction
if expression1
commands (evaluated if expression 1 is true)
elseif expression 2
commands (evaluated if expression 2 is true)
elseif …
.
.
.
else
commands (executed if all previous expressions evaluate to
false)
end

Test Yourself
Create an M-File function with name car2pol which will convert Cartesian co-ordinates to Polar
co-ordinates. For a Cartesian point (x,y), Polar co-ordinate (r,θ) can be found using
𝑦
𝑟 = √𝑥 2 + 𝑦 2 𝜗 = tan−1 (𝑥 )
Angle should be in degrees at output. Show what is output for (1,1), (-1,-3) and (-2,2)
𝑦 𝜋 𝜋
(Recall from your previous knowledge that 𝑡𝑎𝑛−1 (𝑥 ) will give result only from − 2 𝑡𝑜 2 . It is true
if θ is in 1st or 4th quadrant. And if θ is in 2nd or 3rd quadrant you have to add π in the result. So if
x is +ve (1st and 4th Quadrant), result is correct and if x is –ve (2nd and 3rd Quadrant), you have to
add π to it. Use if-else condition to handle it )

MCT-244L: Signal Processing


Department of Mechatronics and Control Engineering, U.E.T Lahore
M-File Commands Output

For Loop:
You people are well familiar with for loop in programming languages. Its syntax is
for expression
statements
end

Suppose that one-need values of the sine function at eleven evenly spaced points πn/10, for n =
0, 1, … 10. To generate the numbers in question for loop can be used as:
for n=0:10
x(n+1) = sin(pi*n/10);
end

The for loops can be nested.

Test Yourself
Run following nested for loop and write down its output:
H = zeros(5);
H=
for m=1:5
for n=1:5
H(m,n) = 1/(m+n-1);
end
end
H

MCT-244L: Signal Processing


Department of Mechatronics and Control Engineering, U.E.T Lahore
Test Yourself
In above task, matrix H has element H (3, 3) =0.2000. Explain below why it came out to be 0.2000

MCT-244L: Signal Processing


Department of Mechatronics and Control Engineering, U.E.T Lahore

You might also like