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

MATLAB Skill Book May 9

The document describes a value added course on MATLAB programming being offered at KPR Institute of Engineering and Technology. The course aims to introduce undergraduate students to computational methods using MATLAB. Over the course, students will learn MATLAB programming basics, numerical methods for engineering problems, and how to use MATLAB to solve computational problems. The schedule outlines topics to be covered each day including matrices, plotting, functions, transforms, and applications.

Uploaded by

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

MATLAB Skill Book May 9

The document describes a value added course on MATLAB programming being offered at KPR Institute of Engineering and Technology. The course aims to introduce undergraduate students to computational methods using MATLAB. Over the course, students will learn MATLAB programming basics, numerical methods for engineering problems, and how to use MATLAB to solve computational problems. The schedule outlines topics to be covered each day including matrices, plotting, functions, transforms, and applications.

Uploaded by

jaishankar1977
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 62

1

KPR INSTITUTE OF ENGINEERING AND TECHNOLOGY


(Affiliated to Anna University, Chennai, Approved by AICTE, Accredited by NAAC
with A Grade)
Coimbatore – 641 407

Department of Electronics and Communication Engineering

VALUE ADDED COURSE ON

MATLAB PROGRAMMING

Course Coordinators

Dr.B.Jaishankar, ASP/ECE

Mr.M.Santhanaraj, AP/ECE

Mr.G.K.Jakir Hussain, AP/ECE


2

About the Course

MATLAB is a popular language for numerical computation. This course introduces students to
MATLAB programming, and demonstrate its use for scientific computations. The basis of
computational techniques are expounded through various coding examples and problems, and
practical ways to use MATLAB will be discussed.

Course Objective

The objective of this course is to introduce undergraduate students to computational methods using
MATLAB.

Course Outcome
At the end of the course a student would

 Learn basics of MATLAB programming


 Get introduced to numerical methods for engineering problems
 Use MATLAB to solve computational problems

Pre-Requisites
The students for this course are expected to know basics of linear algebra and calculus.
3

CONTENTS

S.No Title Page No.

1 Pre assessment

2 Introduction to MATLAB

3 Operations on Matrices

4 Basic Tools

5 Flow control

6 Functions and Logic

7 Algebraic and Mathematical equations

8 Transforms

9 Real time applications of MATLAB (1D and 2D)

10 Post assessment
4

Schedule

Day 09.00 am-10.30 11.00 am-12.30 01.30 pm – 03.00 03.30 pm-05.00 pm


am pm pm
1 Pre assessment Simple Basic Commands Practice Session
and Introduction expressions and
variables
2 Accessing Matrix Tea Assigning into Lunch Matrix Tea Plotting and formatting
Elements Break Submatrices
\ Break Concatenations and Break text
operators
3 If and for loop Logic functions Solving Practice Session
statements mathematical
equations
4 Introduction to 1D Addition and Image processing Practice session and Post
and 2D signals removal of noise operations assessment
from speech
signal
5

Pre assessment

1. Do you know MATLAB software? Yes/No


2. Solve the equation : x2-7x+10

3. Solve 5x+9y=5; 3x-6y=4

4. Differentiate 3t2+2t-2

5. Integrate (i) cos x (ii) exp(x) (iii) Log x

INTRODUCTION TO MATLAB

MATLAB (matrix laboratory) is a fourth-generation high-level programming language and


interactive environment for numerical computation, visualization and programming. MATLAB is
developed by MathWorks.

It allows matrix manipulations; plotting of functions and data; implementation of algorithms;


creation of user interfaces; interfacing with programs written in other languages, including C, C++,
Java, and FORTRAN; analyze data; develop algorithms; and create models and applications.

It has numerous built-in commands and math functions that help you in mathematical calculations,
generating plots, and performing numerical methods.

MATLAB's Power of Computational Mathematics


MATLAB is used in every facet of computational mathematics. Following are some commonly
used mathematical calculations where it is used most commonly −

 Dealing with Matrices and Arrays


 2-D and 3-D Plotting and graphics
 Linear Algebra
 Algebraic Equations
 Non-linear Functions
 Statistics
 Data Analysis
 Calculus and Differential Equations
 Integration
 Transforms
 Curve Fitting
 Various other special functions
6

Features of MATLAB
Following are the basic features of MATLAB −

 It is a high-level language for numerical computation, visualization and application


development.

 It also provides an interactive environment for iterative exploration, design and problem
solving.

 It provides vast library of mathematical functions for linear algebra, statistics, Fourier
analysis, filtering, optimization, numerical integration and solving ordinary differential
equations.

 It provides built-in graphics for visualizing data and tools for creating custom plots.

 MATLAB's programming interface gives development tools for improving code quality
maintainability and maximizing performance.

 It provides tools for building applications with custom graphical interfaces.

 It provides functions for integrating MATLAB based algorithms with external applications
and languages such as C, Java, .NET and Microsoft Excel.

Uses of MATLAB
MATLAB is widely used as a computational tool in science and engineering encompassing the
fields of physics, chemistry, math and all engineering streams. It is used in a range of applications
including −

 Signal Processing and Communications


 Image and Video Processing
 Control Systems
 Test and Measurement
 Computational Finance
 Computational Biology
Local Environment Setup
Setting up MATLAB environment is a matter of few clicks. The installer can be downloaded
from here.

MathWorks provides the licensed product, a trial version and a student version as well. You need
to log into the site and wait a little for their approval.

After downloading the installer the software can be installed through few clicks.
7

Understanding the MATLAB Environment


MATLAB development IDE can be launched from the icon created on the desktop. The main
working window in MATLAB is called the desktop. When MATLAB is started, the desktop
appears in its default layout −
8

The desktop has the following panels −

 Current Folder − This panel allows you to access the project folders and files.

 Command Window − This is the main area where commands can be entered at the
command line. It is indicated by the command prompt (>>).

 Workspace − The workspace shows all the variables created and/or imported from files.
9

 Command History − This panel shows or return commands that are entered at the command
line.

MATLAB environment behaves like a super-complex calculator. You can enter commands at the
>> command prompt.

MATLAB is an interpreted environment. In other words, you give a command and MATLAB
executes it right away.

Hands on Practice
Type a valid expression, for example,

5+5

And press ENTER

When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the
result returned is −

ans = 10
Let us take up few more examples −

3^2 % 3 raised to the power of 2

When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the
result returned is −

ans = 9
Another example,

sin(pi /2) % sine of angle 90o

When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the
result returned is −
10

ans = 1
Another example,

7/0 % Divide by zero

When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the
result returned is −

ans = Inf
warning: division by zero
Another example,

732 * 20.3

When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the
result returned is −

ans = 1.4860e+04
MATLAB provides some special expressions for some mathematical symbols, like pi for π, Inf for
∞, i (and j) for √-1 etc. Nan stands for 'not a number'.

Use of Semicolon (;) in MATLAB


Semicolon (;) indicates end of statement. However, if you want to suppress and hide the MATLAB
output for an expression, add a semicolon after the expression.

For example,

x = 3;

y=x+5

When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the
result returned is −

y= 8

Adding Comments
The percent symbol (%) is used for indicating a comment line. For example,

x=9 % assign the value 9 to x

You can also write a block of comments using the block comment operators % { and % }.

The MATLAB editor includes tools and context menu items to help you add, remove, or change
the format of comments.
11

Naming Variables
Variable names consist of a letter followed by any number of letters, digits or underscore.

MATLAB is case-sensitive.

Variable names can be of any length, however, MATLAB uses only first N characters, where N is
given by the function namelengthmax.

Saving Your Work


The save command is used for saving all the variables in the workspace, as a file with .mat
extension, in the current directory.

For example,

save myfile
You can reload the file anytime later using the load command.

load myfile

MATLAB – VARIABLES
In MATLAB environment, every variable is an array or matrix.

You can assign variables in a simple way. For example,

x=3 % defining x and initializing it with a value

MATLAB will execute the above statement and return the following result −

x=3
It creates a 1-by-1 matrix named x and stores the value 3 in its element. Let us check another
example,

x = sqrt(16) % defining x and initializing it with an expression

MATLAB will execute the above statement and return the following result −

x=4
Please note that −

 Once a variable is entered into the system, you can refer to it later.

 Variables must have values before they are used.

 When an expression returns a result that is not assigned to any variable, the system assigns
it to a variable named ans, which can be used later.

For example,

sqrt(78)
12

MATLAB will execute the above statement and return the following result −

ans = 8.8318
You can use this variable ans −

sqrt(78);

9876/ans

MATLAB will execute the above statement and return the following result −

ans = 1118.2
Let's look at another example −

x = 7 * 8;

y = x * 7.89

MATLAB will execute the above statement and return the following result −

y = 441.84

Multiple Assignments
You can have multiple assignments on the same line. For example,

a = 2; b = 7; c = a * b

MATLAB will execute the above statement and return the following result −

c = 14

I have forgotten the Variables!


The who command displays all the variable names you have used.

who
MATLAB will execute the above statement and return the following result −

Your variables are:


a ans b c
The whos command displays little more about the variables −

 Variables currently in memory


 Type of each variables
 Memory allocated to each variable
 Whether they are complex variables or not
whos
MATLAB will execute the above statement and return the following result −
13

Attr Name Size Bytes Class


==== ==== ==== ==== =====
a 1x1 8 double
ans 1x70 757 cell
b 1x1 8 double
c 1x1 8 double

Total is 73 elements using 781 bytes


The clear command deletes all (or the specified) variable(s) from the memory.

clear x % it will delete x, won't display anything


clear % it will delete all variables in the workspace
% peacefully and unobtrusively

Long Assignments
Long assignments can be extended to another line by using an ellipses (...). For example,

initial_velocity = 0;

acceleration = 9.8;

time = 20;

final_velocity = initial_velocity + acceleration * time

MATLAB will execute the above statement and return the following result −

final_velocity = 196

The format Command


By default, MATLAB displays numbers with four decimal place values. This is known as short
format.

However, if you want more precision, you need to use the format command.

The format long command displays 16 digits after decimal.

For example −

format long

x = 7 + 10/3 + 5 ^ 1.2

MATLAB will execute the above statement and return the following result−

x = 17.2319816406394
Another example,

format short

x = 7 + 10/3 + 5 ^ 1.2
14

MATLAB will execute the above statement and return the following result −

x = 17.232
The format bank command rounds numbers to two decimal places. For example,

format bank

daily_wage = 177.45;

weekly_wage = daily_wage * 6

MATLAB will execute the above statement and return the following result −

weekly_wage = 1064.70
MATLAB displays large numbers using exponential notation.

The format short e command allows displaying in exponential form with four decimal places plus
the exponent.

For example,

format short e

4.678 * 4.9

MATLAB will execute the above statement and return the following result −

ans = 2.2922e+01
The format long e command allows displaying in exponential form with four decimal places plus
the exponent. For example,

format long e

x = pi

MATLAB will execute the above statement and return the following result −

x = 3.141592653589793e+00
The format rat command gives the closest rational expression resulting from a calculation. For
example,

format rat

4.678 * 4.9

MATLAB will execute the above statement and return the following result −

ans = 34177/1491
15

Creating Vectors
A vector is a one-dimensional array of numbers. MATLAB allows creating two types of vectors −

 Row vectors
 Column vectors
Row vectors are created by enclosing the set of elements in square brackets, using space or comma
to delimit the elements.

For example,

r = [7 8 9 10 11]

MATLAB will execute the above statement and return the following result −

r=

7 8 9 10 11
Another example,

r = [7 8 9 10 11];

t = [2, 3, 4, 5, 6];

res = r + t

MATLAB will execute the above statement and return the following result −

res =

9 11 13 15 17
Column vectors are created by enclosing the set of elements in square brackets, using semicolon(;)
to delimit the elements.

c = [7; 8; 9; 10; 11]

MATLAB will execute the above statement and return the following result −

c=
7
8
9
10
11

Creating Matrices
A matrix is a two-dimensional array of numbers.
16

In MATLAB, a matrix is created by entering each row as a sequence of space or comma separated
elements, and end of a row is demarcated by a semicolon. For example, let us create a 3-by-3 matrix
as −

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

MATLAB will execute the above statement and return the following result −

m=
1 2 3
4 5 6
7 8 9

MATLAB – COMMANDS
MATLAB is an interactive program for numerical computation and data visualization. You can
enter a command by typing it at the MATLAB prompt '>>' on the Command Window.

In this section, we will provide lists of commonly used general MATLAB commands.

Commands for Managing a Session


MATLAB provides various commands for managing a session. The following table provides all
such commands −

Command Purpose

clc Clears command window.

clear Removes variables from memory.

exist Checks for existence of file or variable.

global Declares variables to be global.

help Searches for a help topic.

lookfor Searches help entries for a keyword.

quit Stops MATLAB.

who Lists current variables.


17

whos Lists current variables (long display).

Commands for Working with the System


MATLAB provides various useful commands for working with the system, like saving the current
work in the workspace as a file and loading the file later.

It also provides various commands for other system-related activities like, displaying date, listing
files in the directory, displaying current directory, etc.

The following table displays some commonly used system-related commands −

Command Purpose

cd Changes current directory.

date Displays current date.

delete Deletes a file.

diary Switches on/off diary file recording.

dir Lists all files in current directory.

load Loads workspace variables from a file.

path Displays search path.

pwd Displays current directory.

save Saves workspace variables in a file.

type Displays contents of a file.

what Lists all MATLAB files in the current directory.

wklread Reads .wk1 spreadsheet file.


18

Input and Output Commands


MATLAB provides the following input and output related commands −

Command Purpose

disp Displays contents of an array or string.

fscanf Read formatted data from a file.

format Controls screen-display format.

fprintf Performs formatted writes to screen or file.

input Displays prompts and waits for input.

; Suppresses screen printing.

The fscanf and fprintf commands behave like C scanf and printf functions. They support the
following format codes −

Format Code Purpose

%s Format as a string.

%d Format as an integer.

%f Format as a floating point value.

%e Format as a floating point value in scientific notation.

%g Format in the most compact form: %f or %e.

\n Insert a new line in the output string.

\t Insert a tab in the output string.


19

The format function has the following forms used for numeric display −

Format Function Display up to

format short Four decimal digits (default).

format long 16 decimal digits.

format short e Five digits plus exponent.

format long e 16 digits plus exponents.

format bank Two decimal digits.

format + Positive, negative, or zero.

format rat Rational approximation.

format compact Suppresses some line feeds.

format loose Resets to less compact display mode.

Vector, Matrix and Array Commands


The following table shows various commands used for working with arrays, matrices and vectors

Command Purpose

cat Concatenates arrays.

find Finds indices of nonzero elements.

length Computes number of elements.


20

linspace Creates regularly spaced vector.

logspace Creates logarithmically spaced vector.

max Returns largest element.

min Returns smallest element.

prod Product of each column.

reshape Changes size.

size Computes array size.

sort Sorts each column.

sum Sums each column.

eye Creates an identity matrix.

ones Creates an array of ones.

zeros Creates an array of zeros.

cross Computes matrix cross products.

dot Computes matrix dot products.

det Computes determinant of an array.

inv Computes inverse of a matrix.

pinv Computes pseudoinverse of a matrix.


21

rank Computes rank of a matrix.

rref Computes reduced row echelon form.

cell Creates cell array.

celldisp Displays cell array.

cellplot Displays graphical representation of cell array.

num2cell Converts numeric array to cell array.

deal Matches input and output lists.

iscell Identifies cell array.

Plotting Commands
MATLAB provides numerous commands for plotting graphs. The following table shows some of
the commonly used commands for plotting −

Command Purpose

axis Sets axis limits.

fplot Intelligent plotting of functions.

grid Displays gridlines.

plot Generates xy plot.

print Prints plot or saves plot to a file.

title Puts text at top of plot.


22

xlabel Adds text label to x-axis.

ylabel Adds text label to y-axis.

axes Creates axes objects.

close Closes the current plot.

close all Closes all plots.

figure Opens a new figure window.

gtext Enables label placement by mouse.

hold Freezes current plot.

legend Legend placement by mouse.

refresh Redraws current figure window.

set Specifies properties of objects such as axes.

subplot Creates plots in subwindows.

text Places string in figure.

bar Creates bar chart.

loglog Creates log-log plot.

polar Creates polar plot.

semilogx Creates semilog plot. (logarithmic abscissa).


23

semilogy Creates semilog plot. (logarithmic ordinate).

stairs Creates stairs plot.

stem Creates stem plot.

VECTOR AND ITS OPERATIONS


A vector is a one-dimensional array of numbers. MATLAB allows creating two types of vectors −

 Row vectors
 Column vectors
Row Vectors
Row vectors are created by enclosing the set of elements in square brackets, using space or comma
to delimit the elements.

r = [7 8 9 10 11]

MATLAB will execute the above statement and return the following result −

r=

7 8 9 10 11

Column Vectors
Column vectors are created by enclosing the set of elements in square brackets, using semicolon
to delimit the elements.

c = [7; 8; 9; 10; 11]

MATLAB will execute the above statement and return the following result −

c=
7
8
9
10
11

Referencing the Elements of a Vector


You can reference one or more of the elements of a vector in several ways. The ith component of a
vector v is referred as v(i). For example

v = [ 1; 2; 3; 4; 5; 6]; % creating a column vector of 6 elements


24

v(3)

MATLAB will execute the above statement and return the following result

ans = 3
When you reference a vector with a colon, such as v(:), all the components of the vector are listed.

v = [ 1; 2; 3; 4; 5; 6]; % creating a column vector of 6 elements

v(:)

MATLAB will execute the above statement and return the following result

ans =
1
2
3
4
5
6
MATLAB allows you to select a range of elements from a vector.

For example, let us create a row vector rv of 9 elements, then we will reference the elements 3 to 7
by writing rv(3:7) and create a new vector named sub_rv.

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

sub_rv = rv(3:7)

MATLAB will execute the above statement and return the following result

sub_rv =

3 4 5 6 7

MATRIX
A matrix is a two-dimensional array of numbers.

In MATLAB, you create a matrix by entering elements in each row as comma or space delimited
numbers and using semicolons to mark the end of each row.

For example, let us create a 4-by-5 matrix a

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

MATLAB will execute the above statement and return the following result

a=
1 2 3 4 5
2 3 4 5 6
25

3 4 5 6 7
4 5 6 7 8

Referencing the Elements of a Matrix


To reference an element in the mth row and nth column, of a matrix mx, we write

mx(m, n);
For example, to refer to the element in the 2nd row and 5th column, of the matrix a, as created in the
last section, we type

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

a(2,5)

MATLAB will execute the above statement and return the following result

ans = 6
To reference all the elements in the mth column we type A(:,m).

Let us create a column vector v, from the elements of the 4th row of the matrix a

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

v = a(:,4)

MATLAB will execute the above statement and return the following result

v=
4
5
6
7
You can also select the elements in the mth through nth columns, for this we write

a(:,m:n)

Let us create a smaller matrix taking the elements from the second and third columns

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

a(:, 2:3)

MATLAB will execute the above statement and return the following result

ans =
2 3
3 4
4 5
5 6
In the same way, you can create a sub-matrix taking a sub-part of a matrix.
26

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

a(:, 2:3)

MATLAB will execute the above statement and return the following result

ans =
2 3
3 4
4 5
5 6
In the same way, you can create a sub-matrix taking a sub-part of a matrix.

For example, let us create a sub-matrix sa taking the inner subpart of a

3 4 5
4 5 6
To do this, write

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

sa = a(2:3,2:4)

MATLAB will execute the above statement and return the following result

sa =
3 4 5
4 5 6

Deleting a Row or a Column in a Matrix


You can delete an entire row or column of a matrix by assigning an empty set of square braces []
to that row or column. Basically, [] denotes an empty array.

For example, let us delete the fourth row of a

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

a( 4 , : ) = []

MATLAB will execute the above statement and return the following result

a=
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
Next, let us delete the fifth column of a

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

a(: , 5)=[]

MATLAB will execute the above statement and return the following result

a=
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7

Example
In this example, let us create a 3-by-3 matrix m, then we will copy the second and third rows of this
matrix twice to create a 4-by-3 matrix.

Create a script file with the following code

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

new_mat = a([2,3,2,3],:)

When you run the file, it displays the following result

new_mat =
4 5 6
7 8 9
4 5 6
7 8 9

ARRAYS

All variables of all data types in MATLAB are multidimensional arrays. A vector is a one-
dimensional array and a matrix is a two-dimensional array.

We have already discussed vectors and matrices. In this chapter, we will discuss multidimensional
arrays. However, before that, let us discuss some special types of arrays.

Special Arrays in MATLAB


In this section, we will discuss some functions that create some special arrays. For all these
functions, a single argument creates a square array, double arguments create rectangular array.

The zeros() function creates an array of all zeros, for example

zeros(5)

MATLAB will execute the above statement and return the following result

ans =
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
28

0 0 0 0 0
The ones() function creates an array of all ones

For example

ones(4,3)

MATLAB will execute the above statement and return the following result

ans =
1 1 1
1 1 1
1 1 1
1 1 1
The eye() function creates an identity matrix.

For example

eye(4)

MATLAB will execute the above statement and return the following result

ans =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
The rand() function creates an array of uniformly distributed random numbers on (0,1)

For example

rand(3, 5)

MATLAB will execute the above statement and return the following result

ans =
0.8147 0.9134 0.2785 0.9649 0.9572
0.9058 0.6324 0.5469 0.1576 0.4854
0.1270 0.0975 0.9575 0.9706 0.8003

A Magic Square
A magic square is a square that produces the same sum, when its elements are added row-wise,
column-wise or diagonally.

The magic() function creates a magic square array. It takes a singular argument that gives the size
of the square. The argument must be a scalar greater than or equal to 3.

magic(4)
29

MATLAB will execute the above statement and return the following result

ans =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1

Multidimensional Arrays
An array having more than two dimensions is called a multidimensional array in MATLAB.
Multidimensional arrays in MATLAB are an extension of the normal two-dimensional matrix.

Generally, to generate a multidimensional array, we first create a two-dimensional array and extend
it.

For example, let's create a two-dimensional array a.

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

MATLAB will execute the above statement and return the following result

a=
7 9 5
6 1 9
4 3 2
The array a is a 3-by-3 array; we can add a third dimension to a, by providing the values like

a(:, :, 2)= [ 1 2 3; 4 5 6; 7 8 9]

MATLAB will execute the above statement and return the following result

a=

ans(:,:,1) =

0 0 0
0 0 0
0 0 0

ans(:,:,2) =

1 2 3
4 5 6
7 8 9
We can also create multidimensional arrays using the ones(), zeros() or the rand() functions.

For example,

b = rand(4,3,2)
30

MATLAB will execute the above statement and return the following result

b(:,:,1) =
0.0344 0.7952 0.6463
0.4387 0.1869 0.7094
0.3816 0.4898 0.7547
0.7655 0.4456 0.2760

b(:,:,2) =
0.6797 0.4984 0.2238
0.6551 0.9597 0.7513
0.1626 0.3404 0.2551
0.1190 0.5853 0.5060
We can also use the cat() function to build multidimensional arrays. It concatenates a list of arrays
along a specified dimension.

Syntax for the cat() function is

B = cat(dim, A1, A2...)

Where,

 B is the new array created

 A1, A2, ... are the arrays to be concatenated

 dim is the dimension along which to concatenate the arrays

Example
Create a script file and type the following code into it

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

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

c = cat(3, a, b, [ 2 3 1; 4 7 8; 3 9 0])

When you run the file, it displays

c(:,:,1) =
9 8 7
6 5 4
3 2 1
c(:,:,2) =
1 2 3
4 5 6
7 8 9
c(:,:,3) =
2 3 1
4 7 8
3 9 0
31

Array Functions
MATLAB provides the following functions to sort, rotate, permute, reshape, or shift array contents.

Function Purpose

length Length of vector or largest array dimension

ndims Number of array dimensions

numel Number of array elements

size Array dimensions

iscolumn Determines whether input is column vector

isempty Determines whether array is empty

ismatrix Determines whether input is matrix

isrow Determines whether input is row vector

isscalar Determines whether input is scalar

isvector Determines whether input is vector

blkdiag Constructs block diagonal matrix from input arguments

circshift Shifts array circularly

ctranspose Complex conjugate transpose

diag Diagonal matrices and diagonals of matrix

flipdim Flips array along specified dimension


32

fliplr Flips matrix from left to right

flipud Flips matrix up to down

ipermute Inverses permute dimensions of N-D array

permute Rearranges dimensions of N-D array

repmat Replicates and tile array

reshape Reshapes array

rot90 Rotates matrix 90 degrees

shiftdim Shifts dimensions

issorted Determines whether set elements are in sorted order

sort Sorts array elements in ascending or descending order

sortrows Sorts rows in ascending order

squeeze Removes singleton dimensions

transpose Transpose

vectorize Vectorizes expression

Examples
The following examples illustrate some of the functions mentioned above.

Length, Dimension and Number of elements

Create a script file and type the following code into it

x = [7.1, 3.4, 7.2, 28/4, 3.6, 17, 9.4, 8.9];

length(x) % length of x vector


33

y = rand(3, 4, 5, 2);

ndims(y) % no of dimensions in array y

s = ['Zara', 'Nuha', 'Shamim', 'Riz', 'Shadab'];

numel(s) % no of elements in s

When you run the file, it displays the following result

ans = 8
ans = 4
ans = 23
Circular Shifting of the Array Elements

Create a script file and type the following code into it

a = [1 2 3; 4 5 6; 7 8 9] % the original array a

b = circshift(a,1) % circular shift first dimension values down by 1.

c = circshift(a,[1 -1]) % circular shift first dimension values % down by 1

% and second dimension values to the left % by 1.

When you run the file, it displays the following result

a=
1 2 3
4 5 6
7 8 9

b=
7 8 9
1 2 3
4 5 6

c=
8 9 7
2 3 1
5 6 4

Sorting Arrays
Create a script file and type the following code into it

v = [ 23 45 12 9 5 0 19 17] % horizontal vector

sort(v) % sorting v

m = [2 6 4; 5 3 9; 2 0 1] % two dimensional array

sort(m, 1) % sorting m along the row

sort(m, 2) % sorting m along the column


34

When you run the file, it displays the following result

v=
23 45 12 9 5 0 19 17
ans =
0 5 9 12 17 19 23 45
m=
2 6 4
5 3 9
2 0 1
ans =
2 0 1
2 3 4
5 6 9
ans =
2 4 6
3 5 9
0 1 2

Cell Array
Cell arrays are arrays of indexed cells where each cell can store an array of a different dimensions
and data types.

The cell function is used for creating a cell array. Syntax for the cell function is

C = cell(dim)

C = cell(dim1,...,dimN)

D = cell(obj)

Where,
 C is the cell array;

 dim is a scalar integer or vector of integers that specifies the dimensions of cell array C;

 dim1, ... , dimN are scalar integers that specify the dimensions of C;

 obj is One of the following

o Java array or object


o .NET array of type System.String or System.Object
Example
Create a script file and type the following code into it

c = cell(2, 5);

c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5}

When you run the file, it displays the following result


35

c=
{
[1,1] = Red
[2,1] = 1
[1,2] = Blue
[2,2] = 2
[1,3] = Green
[2,3] = 3
[1,4] = Yellow
[2,4] = 4
[1,5] = White
[2,5] = 5
}

Accessing Data in Cell Arrays


There are two ways to refer to the elements of a cell array

 Enclosing the indices in first bracket (), to refer to sets of cells


 Enclosing the indices in braces {}, to refer to the data within individual cells
When you enclose the indices in first bracket, it refers to the set of cells.

Cell array indices in smooth parentheses refer to sets of cells.

For example

c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5};

c(1:2,1:2)

MATLAB will execute the above statement and return the following result

ans =
{
[1,1] = Red
[2,1] = 1
[1,2] = Blue
[2,2] = 2
}
You can also access the contents of cells by indexing with curly braces.

For example

c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5};

c{1, 2:4}

MATLAB will execute the above statement and return the following result
36

ans = Blue
ans = Green
ans = Yellow

COLON NOTATION
The colon(:) is one of the most useful operator in MATLAB. It is used to create vectors, subscript
arrays, and specify for iterations.

If you want to create a row vector, containing integers from 1 to 10, you write

1:10

MATLAB executes the statement and returns a row vector containing the integers from 1 to 10

ans =

1 2 3 4 5 6 7 8 9 10
If you want to specify an increment value other than one, for example

100: -5: 50

MATLAB executes the statement and returns the following result

ans =
100 95 90 85 80 75 70 65 60 55 50
Let us take another example

0:pi/8:pi

MATLAB executes the statement and returns the following result

ans =
Columns 1 through 7
0 0.3927 0.7854 1.1781 1.5708 1.9635 2.3562
Columns 8 through 9
2.7489 3.1416
You can use the colon operator to create a vector of indices to select rows, columns or elements of
arrays.

The following table describes its use for this purpose (let us have a matrix A)
37

Format Purpose

A(:,j) is the jth column of A.

A(i,:) is the ith row of A.

A(:,:) is the equivalent two-dimensional array. For matrices this is the same as A.

A(j:k) is A(j), A(j+1),...,A(k).

A(:,j:k) is A(:,j), A(:,j+1),...,A(:,k).

A(:,:,k) is the kth page of three-dimensional array A.

A(i,j,k,:) is a vector in four-dimensional array A. The vector includes A(i,j,k,1),


A(i,j,k,2), A(i,j,k,3), and so on.

A(:) is all the elements of A, regarded as a single column. On the left side of an
assignment statement, A(:) fills A, preserving its shape from before. In this
case, the right side must contain the same number of elements as A.

Example: Create a script file and type the following code in it

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

A(:,2) % second column of A

A(:,2:3) % second and third column of A

A(2:3,2:3) % second and third rows and second and third columns

When you run the file, it displays the following result

A=
1 2 3 4
4 5 6 7
7 8 9 10

ans =
2
5
8

ans =
38

2 3
5 6
8 9

ans =
5 6
8 9

PLOTTING

To plot the graph of a function, you need to take the following steps:

 Define x, by specifying the range of values for the variable x, for which the function is to
be plotted

 Define the function, y = f(x)

 Call the plot command, as plot(x, y)

Following example would demonstrate the concept. Let us plot the simple function y = x for the
range of values for x from 0 to 100, with an increment of 5.

Create a script file and type the following code

x = [0:5:100];

y = x;

plot(x, y)

When you run the file, MATLAB displays the following plot

Let us take one more example to plot the function y = x2. In this example, we will draw two graphs
with the same function, but in second time, we will reduce the value of increment. Please note that
as we decrease the increment, the graph becomes smoother.
39

Create a script file and type the following code

x = [1 2 3 4 5 6 7 8 9 10];

x = [-100:20:100];

y = x.^2;

plot(x, y)

When you run the file, MATLAB displays the following plot

Change the code file a little, reduce the increment to 5

x = [-100:5:100];

y = x.^2;

plot(x, y)

MATLAB draws a smoother graph

Adding Title, Labels, Grid Lines and Scaling on the Graph


MATLAB allows you to add title, labels along the x-axis and y-axis, grid lines and also to adjust
the axes to spruce up the graph.
40

 The xlabel and ylabel commands generate labels along x-axis and y-axis.

 The title command allows you to put a title on the graph.

 The grid on command allows you to put the grid lines on the graph.

 The axis equal command allows generating the plot with the same scale factors and the
spaces on both axes.

 The axis square command generates a square plot.

Example
Create a script file and type the following code

x = [0:0.01:10];

y = sin(x);

plot(x, y), xlabel('x'), ylabel('Sin(x)'), title('Sin(x) Graph'),

grid on, axis equal

MATLAB generates the following graph

Drawing Multiple Functions on the Same Graph


You can draw multiple graphs on the same plot. The following example demonstrates the concept

Example
Create a script file and type the following code

x = [0 : 0.01: 10];

y = sin(x);

g = cos(x);
41

plot(x, y, x, g, '.-'), legend('Sin(x)', 'Cos(x)')

MATLAB generates the following graph

Setting Colors on Graph


MATLAB provides eight basic color options for drawing graphs. The following table shows the
colors and their codes

Code Color

w White

k Black

b Blue

r Red

c Cyan

g Green

m Magenta

y Yellow
42

Example
Let us draw the graph of two polynomials

 f(x) = 3x4 + 2x3+ 7x2 + 2x + 9 and

 g(x) = 5x3 + 9x + 2

Create a script file and type the following code

x = [-10 : 0.01: 10];

y = 3*x.^4 + 2 * x.^3 + 7 * x.^2 + 2 * x + 9;

g = 5 * x.^3 + 9 * x + 2;

plot(x, y, 'r', x, g, 'g')

When you run the file, MATLAB generates the following graph

Setting Axis Scales


The axis command allows you to set the axis scales. You can provide minimum and maximum
values for x and y axes using the axis command in the following way

axis ( [xmin xmax ymin ymax] )


The following example shows this

Example
Create a script file and type the following code

x = [0 : 0.01: 10];

y = exp(-x).* sin(2*x + 3);

plot(x, y), axis([0 10 -1 1])

When you run the file, MATLAB generates the following graph
43

Generating Sub-Plots
When you create an array of plots in the same figure, each of these plots is called a subplot.
The subplot command is used for creating subplots.

Syntax for the command is

subplot(m, n, p)
where, m and n are the number of rows and columns of the plot array and pspecifies where to put a
particular plot.

Each plot created with the subplot command can have its own characteristics. Following example
demonstrates the concept

Example
Let us generate two plots

y = e−1.5xsin(10x)

y = e−2xsin(10x)

Create a script file and type the following code

x = [0:0.01:5];

y = exp(-1.5*x).*sin(10*x);

subplot(1,2,1)

plot(x,y), xlabel('x'),ylabel('exp(–1.5x)*sin(10x)'),axis([0 5 -1 1])

y = exp(-2*x).*sin(10*x);

subplot(1,2,2)

plot(x,y),xlabel('x'),ylabel('exp(–2x)*sin(10x)'),axis([0 5 -1 1])

When you run the file, MATLAB generates the following graph
44

GRAPHICS

This chapter will continue exploring the plotting and graphics capabilities of MATLAB. We will
discuss:

 Drawing bar charts


 Drawing contours
 Three dimensional plots
Drawing Bar Charts
The bar command draws a two-dimensional bar chart. Let us take up an example to demonstrate
the idea.

Example
Let us have an imaginary classroom with 10 students. We know the percent of marks obtained by
these students are 75, 58, 90, 87, 50, 85, 92, 75, 60 and 95. We will draw the bar chart for this data.

Create a script file and type the following code

x = [1:10];

y = [75, 58, 90, 87, 50, 85, 92, 75, 60, 95];

bar(x,y), xlabel('Student'),ylabel('Score'),

title('First Sem:')

print -deps graph.eps

When you run the file, MATLAB displays the following bar chart
45

Drawing Contours
A contour line of a function of two variables is a curve along which the function has a constant
value. Contour lines are used for creating contour maps by joining points of equal elevation above
a given level, such as mean sea level.

MATLAB provides a contour function for drawing contour maps.

Example
Let us generate a contour map that shows the contour lines for a given function g = f(x, y). This
function has two variables. So, we will have to generate two independent variables, i.e., two data
sets x and y. This is done by calling the meshgrid command.

The meshgrid command is used for generating a matrix of elements that give the range over x and
y along with the specification of increment in each case.

Let us plot our function g = f(x, y), where −5 ≤ x ≤ 5, −3 ≤ y ≤ 3. Let us take an increment of 0.1
for both the values. The variables are set as

[x,y] = meshgrid(–5:0.1:5, –3:0.1:3);

Lastly, we need to assign the function. Let our function be: x2 + y2

Create a script file and type the following code

[x,y] = meshgrid(-5:0.1:5,-3:0.1:3); %independent variables

g = x.^2 + y.^2; % our function

contour(x,y,g) % call the contour function

print -deps graph.eps

When you run the file, MATLAB displays the following contour map
46

Let us modify the code a little to spruce up the map

[x,y] = meshgrid(-5:0.1:5,-3:0.1:3); %independent variables

g = x.^2 + y.^2; % our function

[C, h] = contour(x,y,g); % call the contour function

set(h,'ShowText','on','TextStep',get(h,'LevelStep')*2)

print -deps graph.eps

When you run the file, MATLAB displays the following contour map

Three Dimensional Plots


Three-dimensional plots basically display a surface defined by a function in two variables, g = f
(x,y).

As before, to define g, we first create a set of (x,y) points over the domain of the function using
the meshgrid command. Next, we assign the function itself. Finally, we use the surf command to
create a surface plot.
47

The following example demonstrates the concept

Example
Let us create a 3D surface map for the function g = xe-(x2 + y2)

Create a script file and type the following code

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

g = x .* exp(-x.^2 - y.^2);

surf(x, y, g)

print -deps graph.eps

When you run the file, MATLAB displays the following 3-D map

You can also use the mesh command to generate a three-dimensional surface. However,
the surf command displays both the connecting lines and the faces of the surface in color, whereas,
the mesh command creates a wireframe surface with colored lines connecting the defining points.

DIFFERENTIAL EQUATIONS

MATLAB provides the diff command for computing symbolic derivatives. In its simplest form,
you pass the function you want to differentiate to diff command as an argument.

For example, let us compute the derivative of the function f(t) = 3t2 + 2t-2

Example
Create a script file and type the following code into it

syms t
48

f = 3*t^2 + 2*t^(-2);

diff(f)

When the above code is compiled and executed, it produces the following result

ans =
6*t - 4/t^3

Derivatives of Exponential, Logarithmic and Trigonometric Functions


The following table provides the derivatives of commonly used exponential, logarithmic and
trigonometric functions

Function Derivative

ca.x ca.x.ln c.a (ln is natural logarithm)

ex ex

ln x 1/x

lncx 1/x.ln c

xx xx.(1 + ln x)

sin(x) cos(x)

cos(x) -sin(x)

tan(x) sec2(x), or 1/cos2(x), or 1 + tan2(x)

cot(x) -csc2(x), or -1/sin2(x), or -(1 + cot2(x))

sec(x) sec(x).tan(x)

csc(x) -csc(x).cot(x)

Example
Create a script file and type the following code into it
49

syms x

y = exp(x)

diff(y)

y = x^9

diff(y)

y = sin(x)

diff(y)

y = tan(x)

diff(y)

y = cos(x)

diff(y)

y = log(x)

diff(y)

y = log10(x)

diff(y)

y = sin(x)^2

diff(y)

y = cos(3*x^2 + 2*x + 1)

diff(y)

y = exp(x)/sin(x)
50

diff(y)

When you run the file, MATLAB displays the following result

y=
exp(x)
ans =
exp(x)

y=
x^9
ans =
9*x^8

y=
sin(x)
ans =
cos(x)

y=
tan(x)
ans =
tan(x)^2 + 1

y=
cos(x)
ans =
-sin(x)

y=
log(x)
ans =
1/x

y=
log(x)/log(10)
ans =
1/(x*log(10))

y=
sin(x)^2
ans =
2*cos(x)*sin(x)

y=
cos(3*x^2 + 2*x + 1)
ans =
-sin(3*x^2 + 2*x + 1)*(6*x + 2)

y=
exp(x)/sin(x)
ans =
exp(x)/sin(x) - (exp(x)*cos(x))/sin(x)^2
51

Computing Higher Order Derivatives


To compute higher derivatives of a function f, we use the syntax diff(f,n).

Let us compute the second derivative of the function y = f(x) = x .e-3x

f = x*exp(-3*x);

diff(f, 2)

MATLAB executes the code and returns the following result −

ans =
9*x*exp(-3*x) - 6*exp(-3*x)

Example
In this example, let us solve a problem. Given that a function y = f(x) = 3 sin(x) + 7 cos(5x). We
will have to find out whether the equation f" + f = -5cos(2x) holds true.

Create a script file and type the following code into it

syms x

y = 3*sin(x)+7*cos(5*x); % defining the function

lhs = diff(y,2)+y; %evaluting the lhs of the equation

rhs = -5*cos(2*x); %rhs of the equation

if(isequal(lhs,rhs))

disp('Yes, the equation holds true');

else

disp('No, the equation does not hold true');

end

disp('Value of LHS is: '), disp(lhs);

When you run the file, it displays the following result

No, the equation does not hold true


Value of LHS is:
-168*cos(5*x)

INTEGRATION

Integration deals with two essentially different types of problems.


52

 In the first type, derivative of a function is given and we want to find the function. Therefore,
we basically reverse the process of differentiation. This reverse process is known as anti-
differentiation, or finding the primitive function, or finding an indefinite integral.

 The second type of problems involve adding up a very large number of very small quantities
and then taking a limit as the size of the quantities approaches zero, while the number of
terms tend to infinity. This process leads to the definition of the definite integral.

Definite integrals are used for finding area, volume, center of gravity, moment of inertia, work done
by a force, and in numerous other applications.

Finding Indefinite Integral Using MATLAB


By definition, if the derivative of a function f(x) is f'(x), then we say that an indefinite integral of
f'(x) with respect to x is f(x). For example, since the derivative (with respect to x) of x 2 is 2x, we
can say that an indefinite integral of 2x is x2.

In symbols

f'(x2) = 2x, therefore,

∫ 2xdx = x2.

Indefinite integral is not unique, because derivative of x2 + c, for any value of a constant c, will also
be 2x.

This is expressed in symbols as

∫ 2xdx = x2 + c.

Where, c is called an 'arbitrary constant'.

MATLAB provides an int command for calculating integral of an expression. To derive an


expression for the indefinite integral of a function, we write

int(f);
For example, from our previous example

syms x

int(2*x)

MATLAB executes the above statement and returns the following result

ans =
x^2

Example 1
In this example, let us find the integral of some commonly used expressions. Create a script file
and type the following code in it

syms x n
53

int(sym(x^n))

f = 'sin(n*t)'

int(sym(f))

syms a t

int(a*cos(pi*t))

int(a^x)

When you run the file, it displays the following result

ans =
piecewise([n == -1, log(x)], [n ~= -1, x^(n + 1)/(n + 1)])
f=
sin(n*t)
ans =
-cos(n*t)/n
ans =
(a*sin(pi*t))/pi
ans =
a^x/log(a)

Example 2
Create a script file and type the following code in it

syms x n

int(cos(x))

int(exp(x))

int(log(x))

int(x^-1)

int(x^5*cos(5*x))

pretty(int(x^5*cos(5*x)))

int(x^-5)

int(sec(x)^2)

pretty(int(1 - 10*x + 9 * x^2))

int((3 + 5*x -6*x^2 - 7*x^3)/2*x^2)


54

pretty(int((3 + 5*x -6*x^2 - 7*x^3)/2*x^2))

Note that the pretty function returns an expression in a more readable format.

When you run the file, it displays the following result

ans =
sin(x)

ans =
exp(x)

ans =
x*(log(x) - 1)

ans =
log(x)

ans =
(24*cos(5*x))/3125 + (24*x*sin(5*x))/625 - (12*x^2*cos(5*x))/125 + (x^4*cos(5*x))/5 -
(4*x^3*sin(5*x))/25 + (x^5*sin(5*x))/5
2 4
24 cos(5 x) 24 x sin(5 x) 12 x cos(5 x) x cos(5 x)
----------- + ------------- - -------------- + ------------
3125 625 125 5

3 5

4 x sin(5 x) x sin(5 x)
------------- + -----------
25 5

ans =
-1/(4*x^4)

ans =
tan(x)
2
x (3 x - 5 x + 1)

ans =
- (7*x^6)/12 - (3*x^5)/5 + (5*x^4)/8 + x^3/2

6 5 4 3
7x 3x 5x x
- ---- - ---- + ---- + --
12 5 8 2

Finding Definite Integral Using MATLAB


By definition, definite integral is basically the limit of a sum. We use definite integrals to find areas
such as the area between a curve and the x-axis and the area between two curves. Definite integrals
55

can also be used in other situations, where the quantity required can be expressed as the limit of a
sum.

The int function can be used for definite integration by passing the limits over which you want to
calculate the integral.

To calculate

we write,

int(x, a, b)

For example, to calculate the value of we write

int(x, 4, 9)

MATLAB executes the above statement and returns the following result

ans =
65/2

POLYNOMIALS

MATLAB represents polynomials as row vectors containing coefficients ordered by descending


powers. For example, the equation P(x) = x4 + 7x3 - 5x + 9 could be represented as

p = [1 7 0 -5 9];

Evaluating Polynomials
The polyval function is used for evaluating a polynomial at a specified value. For example, to
evaluate our previous polynomial p, at x = 4, type

p = [1 7 0 -5 9];

polyval(p,4)

MATLAB executes the above statements and returns the following result

ans = 693
MATLAB also provides the polyvalm function for evaluating a matrix polynomial. A matrix
polynomial is a polynomial with matrices as variables.

For example, let us create a square matrix X and evaluate the polynomial p, at X

p = [1 7 0 -5 9];

X = [1 2 -3 4; 2 -5 6 3; 3 1 0 2; 5 -7 3 8];
56

polyvalm(p, X)

MATLAB executes the above statements and returns the following result

ans =
2307 -1769 -939 4499
2314 -2376 -249 4695
2256 -1892 -549 4310
4570 -4532 -1062 9269

Finding the Roots of Polynomials


The roots function calculates the roots of a polynomial. For example, to calculate the roots of our
polynomial p, type

p = [1 7 0 -5 9];

r = roots(p)

MATLAB executes the above statements and returns the following result

r=
-6.8661 + 0.0000i
-1.4247 + 0.0000i
0.6454 + 0.7095i
0.6454 - 0.7095i
The function poly is an inverse of the roots function and returns to the polynomial coefficients. For
example

p2 = poly(r)

MATLAB executes the above statements and returns the following result

p2 =

Columns 1 through 3:

1.00000 + 0.00000i 7.00000 + 0.00000i 0.00000 + 0.00000i

Columns 4 and 5:

-5.00000 - 0.00000i 9.00000 + 0.00000i

Polynomial Curve Fitting


The polyfit function finds the coefficients of a polynomial that fits a set of data in a least-squares
sense. If x and y are two vectors containing the x and y data to be fitted to a n-degree polynomial,
then we get the polynomial fitting the data by writing
57

p = polyfit(x,y,n)

Example
Create a script file and type the following code

x = [1 2 3 4 5 6]; y = [5.5 43.1 128 290.7 498.4 978.67]; %data

p = polyfit(x,y,4) %get the polynomial

% Compute the values of the polyfit estimate over a finer range,

% and plot the estimate over the real data values for comparison:

x2 = 1:.1:6;

y2 = polyval(p,x2);

plot(x,y,'o',x2,y2)

grid on

When you run the file, MATLAB displays the following result

p=
4.1056 -47.9607 222.2598 -362.7453 191.1250
And plots the following graph

APPLICATIONS OF MATLAB USING 1D AND 2D SIGNALS

Speech Signal Processing


load('data');
58

data = data./(max(data)-min(data));
Fs = 8192;
audiowrite('InputData.wav',data,Fs);

Signal translation
Y[n] = x[n-k]
Data_Trans = zeros(length(data)+1000,1);
Data_Trans(1001:end) = data;
subplot 211; plot(data);
axis tight; title('Original Signal');
subplot 212; plot(Data_Trans);
axis tight; title('Translated Signal');

Periodic Noise Removal


[x,fs] = audioread('file1.wav');
Nois = cos(2*pi*2000*linspace(0,2,2*fs));
Yn = x+Nois';
sound(Yn,fs);
subplot 311; plot(x);
axis tight; title('Original Signal');
subplot 312; plot(Yn);
59

axis tight; title('Noisy Signal')


subplot 313; plot(-(fs/2):(fs/2-1),abs(fftshift(fft(Yn,fs))));
axis tight; title('Frequency spectrum of Noisy Signal');

Denoise
B = fir1(101,0.45);
YDenoised = filter(B,1,Yn);
sound(YDenoised);
index = -(fs/2):(fs/2-1);
subplot 311; plot(index,abs(fftshift(fft(Yn,fs))));
axis tight; title('Frequency Spectrum of Noisy Signal');
subplot 312; plot(index,abs(fftshift(fft(B,fs))));
axis tight; title('Frequency Response of LPF');
subplot 313; plot(index,abs(fftshift(fft(YDenoised,fs))));
axis tight; title('Frequency Spectrum of Denoised Signal');

Signal Compression
load('data');
60

data = data./(max(data)-min(data));
fs = length(data);
Data_fft = fft(data,fs);
Data_fft_Trun = Data_fft;
Th = 0.05*max(abs(Data_fft_Trun(:)));
Data_fft_Trun(abs(Data_fft_Trun)<Th) = 0;
NZ = sum(Data_fft_Trun~=0);
data_Recon = ifft(Data_fft_Trun);
CR = length(data)/NZ;
index = -(fs/2):(fs/2-1);
audiowrite('Compressed.wav',Data_Rev,Fs);
disp(['Compression Ratio = ', num2str(CR)]);
subplot 411; plot(data);
axis tight; title('Original Signal');
subplot 412; plot(index,abs(fftshift(Data_fft)));
axis tight; title('DFT coefficients');
subplot 413; plot(index,abs(fftshift(Data_fft_Trun)));
axis tight; title('DFT coefficients after truncation');
subplot 414; plot(data_Recon);
axis tight; title('Reconstructed Signal');
soundsc(data_Recon)
Compression Ratio = 6.1606

Image Processing Toolbox


The Image Processing Toolbox is a collection of functions that extend the capabilities of the
MATLAB’s numeric computing environment. The toolbox supports a wide range of image
processing operations, including:
Geometric operations
61

Neighborhood and block operations


Linear filtering and filter design
Transforms
Image analysis and enhancement
Binary image operations
Region of interest operations
Images in MATLAB
Binary images : {0,1}
• Intensity images : [0,1] or uint8, double etc.
• RGB images : m × n × 3
• Multidimensional images: m × n × p (p is the number of layers)

Image Import and Export


Read and write images in Matlab
img = imread('apple.jpg');
dim = size(img);
figure;
imshow(img);
imwrite(img, 'output.bmp', 'bmp');
Alternatives to imshow
imagesc(I)
imtool(I)
image(I)
Images and Matrices

Binary Image:
row = 256;
col = 256;
img = rand(row, col);
62

img = round(img);
figure;
imshow(img);
size(im)

Post assessment

1. Solve the equation : x2-7x+10 using MATLAB

2. Solve 5x+9y=5; 3x-6y=4 using MATLAB

3. Differentiate 3t2+2t-2 using MATLAB

4. Integrate (i) cos x (ii) exp(x) (iii) Log x using MATLAB

5. Generate Sine wave and plot using MATLAB.

6. Create an image and display its matrix using MATLAB.

7. Create an image and display its histogram.

8. Convert a colour image into Grayscale image.

You might also like