MATLAB Skill Book May 9
MATLAB Skill Book May 9
MATLAB PROGRAMMING
Course Coordinators
Dr.B.Jaishankar, ASP/ECE
Mr.M.Santhanaraj, AP/ECE
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
Pre-Requisites
The students for this course are expected to know basics of linear algebra and calculus.
3
CONTENTS
1 Pre assessment
2 Introduction to MATLAB
3 Operations on Matrices
4 Basic Tools
5 Flow control
8 Transforms
10 Post assessment
4
Schedule
Pre assessment
4. Differentiate 3t2+2t-2
INTRODUCTION TO MATLAB
It has numerous built-in commands and math functions that help you in mathematical calculations,
generating plots, and performing numerical methods.
Features of MATLAB
Following are the basic features of MATLAB −
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 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 −
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
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
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 −
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the
result returned is −
ans = 9
Another example,
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the
result returned is −
10
ans = 1
Another example,
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'.
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,
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.
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.
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,
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.
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
who
MATLAB will execute the above statement and return the following result −
Long Assignments
Long assignments can be extended to another line by using an ellipses (...). For example,
initial_velocity = 0;
acceleration = 9.8;
time = 20;
MATLAB will execute the above statement and return the following result −
final_velocity = 196
However, if you want more precision, you need to use the format command.
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.
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.
Command Purpose
It also provides various commands for other system-related activities like, displaying date, listing
files in the directory, displaying current directory, etc.
Command Purpose
Command Purpose
The fscanf and fprintf commands behave like C scanf and printf functions. They support the
following format codes −
%s Format as a string.
%d Format as an integer.
The format function has the following forms used for numeric display −
Command Purpose
Plotting Commands
MATLAB provides numerous commands for plotting graphs. The following table shows some of
the commonly used commands for plotting −
Command Purpose
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.
MATLAB will execute the above statement and return the following result −
c=
7
8
9
10
11
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(:)
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.
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
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.
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
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.
a = [ 1 2 3 ; 4 5 6; 7 8 9];
new_mat = a([2,3,2,3],:)
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.
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.
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.
Where,
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])
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
transpose Transpose
Examples
The following examples illustrate some of the functions mentioned above.
y = rand(3, 4, 5, 2);
numel(s) % no of elements in s
ans = 8
ans = 4
ans = 23
Circular Shifting of the Array Elements
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
sort(v) % sorting v
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;
c = cell(2, 5);
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
}
For example
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{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
ans =
100 95 90 85 80 75 70 65 60 55 50
Let us take another example
0:pi/8:pi
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(:,:) is the equivalent two-dimensional array. For matrices this is the same as A.
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.
A = [1 2 3 4; 4 5 6 7; 7 8 9 10]
A(2:3,2:3) % second and third rows and second and third columns
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
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.
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
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
x = [-100:5:100];
y = x.^2;
plot(x, y)
The xlabel and ylabel commands generate labels along x-axis and y-axis.
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.
Example
Create a script file and type the following code
x = [0:0.01:10];
y = sin(x);
Example
Create a script file and type the following code
x = [0 : 0.01: 10];
y = sin(x);
g = cos(x);
41
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
g(x) = 5x3 + 9x + 2
g = 5 * x.^3 + 9 * x + 2;
When you run the file, MATLAB generates the following graph
Example
Create a script file and type the following code
x = [0 : 0.01: 10];
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.
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)
x = [0:0.01:5];
y = exp(-1.5*x).*sin(10*x);
subplot(1,2,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:
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.
x = [1:10];
y = [75, 58, 90, 87, 50, 85, 92, 75, 60, 95];
bar(x,y), xlabel('Student'),ylabel('Score'),
title('First Sem:')
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.
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
When you run the file, MATLAB displays the following contour map
46
set(h,'ShowText','on','TextStep',get(h,'LevelStep')*2)
When you run the file, MATLAB displays the following contour map
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
Example
Let us create a 3D surface map for the function g = xe-(x2 + y2)
[x,y] = meshgrid(-2:.2:2);
g = x .* exp(-x.^2 - y.^2);
surf(x, y, g)
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
Function Derivative
ex ex
ln x 1/x
lncx 1/x.ln c
xx xx.(1 + ln x)
sin(x) cos(x)
cos(x) -sin(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
f = x*exp(-3*x);
diff(f, 2)
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.
syms x
if(isequal(lhs,rhs))
else
end
INTEGRATION
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.
In symbols
∫ 2xdx = x2.
Indefinite integral is not unique, because derivative of x2 + c, for any value of a constant c, will also
be 2x.
∫ 2xdx = x2 + c.
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)
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)
Note that the pretty function returns an expression in a more readable format.
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
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)
int(x, 4, 9)
MATLAB executes the above statement and returns the following result
ans =
65/2
POLYNOMIALS
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
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:
Columns 4 and 5:
p = polyfit(x,y,n)
Example
Create a script file and type the following code
% 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
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');
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
Binary Image:
row = 256;
col = 256;
img = rand(row, col);
62
img = round(img);
figure;
imshow(img);
size(im)
Post assessment