0% found this document useful (0 votes)
31 views39 pages

Workshop Manual

The document is a comprehensive guide to MATLAB, covering its basic environment, commands, operators, data types, and functionalities for vector and matrix operations. It includes detailed explanations of decision-making structures, plotting, graphics, and functions within MATLAB. Each chapter is structured with examples and commands to facilitate understanding and practical application.

Uploaded by

Krish
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)
31 views39 pages

Workshop Manual

The document is a comprehensive guide to MATLAB, covering its basic environment, commands, operators, data types, and functionalities for vector and matrix operations. It includes detailed explanations of decision-making structures, plotting, graphics, and functions within MATLAB. Each chapter is structured with examples and commands to facilitate understanding and practical application.

Uploaded by

Krish
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/ 39

Table of Contents

CHAPTER - 1 Basic Matlab Enviornment .......................................................................... 3


1.1 MATLAB Desktop...................................................................................................... 3
1.2 Current Folder .......................................................................................................... 3
1.3 Command Window .................................................................................................. 4
1.4 Workspace ............................................................................................................... 4
1.5 Command History .................................................................................................... 4
CHAPTER - 2 Matlab Basics Commands, Operators & Data Types................................... 5
2.1 General Commands .................................................................................................. 5
2.2 Input and Output Commands .................................................................................. 5
2.3 Colon (:) Operator .................................................................................................... 6
2.4 Arithmetic Operators ............................................................................................... 6
2.5 Relational Operators ................................................................................................ 7
2.6 Logical Operators ..................................................................................................... 8
2.7 Bitwise Operations ................................................................................................... 8
2.7.1 Example ........................................................................................................... 9
2.8 Data Types Available in MATLAB.............................................................................. 9
2.8.1 Example ......................................................................................................... 10
CHAPTER - 3 MATLAB – Vector and Matrix Operations ................................................. 11
3.1 Vector Operations .................................................................................................. 11
3.2 Row Vectors ........................................................................................................... 11
3.3 Column Vectors ...................................................................................................... 11
3.4 Referencing the Elements of a Vector ................................................................... 11
3.5 Matrix Operations .................................................................................................. 12
3.6 Referencing the Elements of a Matrix.................................................................... 15
3.7 Linear Indexing ....................................................................................................... 17
3.8 Deleting a Row or a Column in a Matrix ................................................................ 18
3.8.1 Example ......................................................................................................... 19
CHAPTER - 4 MATLAB - Decision Making ....................................................................... 20
4.1 If-else statements................................................................................................... 20
4.2 Loops ...................................................................................................................... 21
4.2.1 For Loop......................................................................................................... 22
4.2.2 While Loop..................................................................................................... 22

1|Page
4.3 Loop Control Statements ....................................................................................... 22
CHAPTER - 5 MATLAB – Plotting .................................................................................... 24
5.1 Graph Plotting Commands ..................................................................................... 24
5.2 Adding Title, Labels, Grid Lines and Scaling on the Graph ..................................... 26
5.2.1 Example ......................................................................................................... 26
5.3 Drawing Multiple Functions on the Same Graph ................................................... 27
5.3.1 Example ......................................................................................................... 27
5.4 Setting Colors on Graph ......................................................................................... 28
5.4.1 Example ......................................................................................................... 28
5.5 Setting Axis Scales .................................................................................................. 29
5.5.1 Example ......................................................................................................... 29
5.6 Generating Sub-Plots ............................................................................................. 30
5.6.1 Example ......................................................................................................... 30
CHAPTER - 6 MATLAB – Graphics ................................................................................... 31
6.1 Drawing Bar Charts ................................................................................................ 31
6.1.1 Example ......................................................................................................... 31
6.2 Drawing Contours .................................................................................................. 32
6.2.1 Example ......................................................................................................... 32
6.3 Three Dimensional Plots ........................................................................................ 33
6.3.1 Example ......................................................................................................... 33
CHAPTER - 7 MATLAB – Functions ................................................................................. 35
7.1 Example .................................................................................................................. 35
7.2 Anonymous Functions ............................................................................................ 36
7.2.1 Example ......................................................................................................... 36
7.3 Primary and Sub-Functions .................................................................................... 36
7.3.1 Example ......................................................................................................... 37
7.4 Nested Functions ................................................................................................... 37
7.4.1 Example ......................................................................................................... 38
7.5 Private Functions.................................................................................................... 38
7.5.1 Example ......................................................................................................... 38
7.6 Global Variables ..................................................................................................... 39
7.6.1 Example ......................................................................................................... 39

2|Page
CHAPTER - 1 Basic Matlab Environment
1.1 MATLAB Desktop
The main working window in MATLAB is called the desktop. When you start MATLAB,
the desktop appears in its default layout:

The desktop has the following panels:

1.2 Current Folder


This panel allows you to access your project folders and files.

3|Page
1.3 Command Window
This is the main area where you enter commands at the command line, indicated by
the command prompt (>>).

1.4 Workspace
The workspace shows all the variables you create and/or import from files.

1.5 Command History


This panels shows or rerun commands that you entered at the command line.

4|Page
CHAPTER - 2
Matlab Basics Commands, Operators & Data Types
2.1 General Commands
Command Purpose
Clc Clears command window.
Clear Removes variables from memory.
global Declares variables to be global.
Help Searches for a help topic.
Quit Stops MATLAB.
Who Lists current variables.
Whos Lists current variables (long display).

2.2 Input and Output 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.
: Colon Operator.

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.

5|Page
Format Purpose

2.3 Colon (:) Operator


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.

2.4 Arithmetic Operators


MATLAB allows two different types of arithmetic operations −
 Matrix arithmetic operations
 Array arithmetic operations
The matrix operators and array operators are differentiated by the period (.) symbol.
However, as the addition and subtraction operation is same for matrices and arrays,
the operator is same for both cases. The following table gives brief description of the
operators
Operator Description
Addition or unary plus. A+B adds the values stored in variables A
+ and B. A and B must have the same size, unless one is a scalar. A
scalar can be added to a matrix of any size.
Subtraction or unary minus. A-B subtracts the value of B from A. A
- and B must have the same size, unless one is a scalar. A scalar can
be subtracted from a matrix of any size.
Matrix multiplication. C = A*B is the linear algebraic product of the
matrices A and B. More precisely,
*

6|Page
For non-scalar A and B, the number of columns of A must be equal
to the number of rows of B. A scalar can multiply a matrix of any
size.
Array multiplication. A.*B is the element-by-element product of the
.* arrays A and B. A and B must have the same size, unless one of them
is a scalar.
Slash or matrix right division. B/A is roughly the same as B*inv(A).
/
More precisely, B/A = (A'\B')'.
Array right division. A./B is the matrix with elements A(i,j)/B(i,j). A
./
and B must have the same size, unless one of them is a scalar.
Backslash or matrix left division. If A is a square matrix, A\B is
roughly the same as inv(A)*B, except it is computed in a different
way. If A is an n-by-n matrix and B is a column vector with n
\
components, or a matrix with several such columns, then X = A\B is
the solution to the equation AX = B. A warning message is displayed
if A is badly scaled or nearly singular.
Array left division. A.\B is the matrix with elements B(i,j)/A(i,j). A
.\
and B must have the same size, unless one of them is a scalar.
Matrix power. X^p is X to the power p, if p is a scalar. If p is an
integer, the power is computed by repeated squaring. If the integer
^ is negative, X is inverted first. For other values of p, the calculation
involves eigenvalues and eigenvectors, such that if [V,D] = eig(X),
then X^p = V*D.^p/V.
Array power. A.^B is the matrix with elements A(i,j) to the B(i,j)
.^ power. A and B must have the same size, unless one of them is a
scalar.
Matrix transpose. A' is the linear algebraic transpose of A. For
'
complex matrices, this is the complex conjugate transpose.
Array transpose. A.' is the array transpose of A. For complex
.'
matrices, this does not involve conjugation.

2.5 Relational Operators


Relational operators for arrays perform element-by-element comparisons
between two arrays and return a logical array of the same size, with elements set to
logical 1 (true) where the relation is true and elements set to logical 0 (false) where
it is not.
The following table shows the relational operators available in MATLAB:
Operator Description
< Less than
<= Less than or equal to

7|Page
> Greater than
>= Greater than or equal to
== Equal to
~= Not equal to

2.6 Logical Operators


MATLAB offers two types of logical operators and functions:
 Element-wise − These operators operate on corresponding elements of
logical arrays.
 Short-circuit − These operators operate on scalar and, logical expressions.
Element-wise logical operators operate element-by-element on logical arrays. The
symbols &, |, and ~ are the logical array operators AND, OR, and NOT.
Short-circuit logical operators allow short-circuiting on logical operations. The
symbols && and || are the logical short-circuit operators AND and OR.

2.7 Bitwise Operations


Bitwise operators work on bits and perform bit-by-bit operation. The truth
tables for &, |, and ^ are as follows −
P Q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; Now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
MATLAB provides various functions for bit-wise operations like 'bitwise and',
'bitwise or' and 'bitwise not' operations, shift operation, etc.
The following table shows the commonly used bitwise operations:
Function Purpose
bitand(a, b) Bit-wise AND of integers a and b
bitcmp(a) Bit-wise complement of a
bitget(a,pos) Get bit at specified position pos, in the integer array a
bitor(a, b) Bit-wise OR of integers a and b

8|Page
bitset(a, pos) Set bit at specific location pos of a
bitshift(a, k) Returns a shifted to the left by k bits, equivalent to
multiplying by 2k. Negative values of k correspond to shifting
bits right or dividing by 2|k|and rounding to the nearest
integer towards negative infinite. Any overflow bits are
truncated.
bitxor(a, b) Bit-wise XOR of integers a and b
swapbytes Swap byte ordering
2.7.1 Example
Create a script file, and type the following code −
a =5; b =7;
c = a + b
d = c +sin(b)
e =5* d
f =exp(-d)
This gives following result:
c = 12
d = 12.657
e = 63.285
f = 3.1852e-06

2.8 Data Types Available in MATLAB


The following table shows the most commonly used data types in MATLAB
Data Type Description
int8 8-bit signed integer
uint8 8-bit unsigned integer
int16 16-bit signed integer
uint16 16-bit unsigned integer
int32 32-bit signed integer
uint32 32-bit unsigned integer
int64 64-bit signed integer
uint64 64-bit unsigned integer
Single single precision numerical data
double double precision numerical data
logical logical values of 1 or 0, represent true and false respectively
Char character data (strings are stored as vector of characters)
cell array array of indexed cells, each capable of storing an array of a
different dimension and data type

9|Page
structure C-like structures, each structure having named fields capable
of storing an array of a different dimension and data type
2.8.1 Example
Create a script file with the following code −
str='Hello World!'
n =2345
d =double(n)
un= uint32(789.50)
rn=5678.92347
c =int32(rn)
When the above code is compiled and executed, it produces the following result −
str = Hello World!
n = 2345
d = 2345
un = 790
rn = 5678.9
c = 5679

10 | P a g e
CHAPTER - 3
MATLAB –Vector and Matrix Operations
3.1 Vector Operations
A vector is a one-dimensional array of numbers. MATLAB allows creating two types
of vectors
 Row vectors
 Column vectors

3.2 Row Vectors


Row vectors are created by enclosing the set of elements in square brackets, using
space or comma to delimit the elements.
r =[7891011]

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

7 8 9 10 11

3.3 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

3.4 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

v(3) % Execute This Command in Command Prompt


MATLAB will execute the above statement and return the following result −
ans = 3

11 | P a g e
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=[123456789];
sub_rv=rv(3:7)

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

3 4 5 6 7

3.5 Matrix Operations


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 =[12345;23456;34567;45678]
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
4 5 6 7 8

First, let's create a simple vector with 9 elements called a.


a = [1 2 3 4 6 4 3 4 5]
b = a + 2

12 | P a g e
Creating a matrix is as easy as making a vector, using semicolons (;) to separate the
rows of a matrix.
A = [1 2 0; 2 5 -1; 4 10 -1]
A =
1 2 0
2 5 -1
4 10 -1

We can easily find the transpose of the matrix A.


B = A'
B =
1 2 4
2 5 10
0 -1 -1

Now let's multiply these two matrices together.


C = A * B
C =
5 12 24
12 30 59
24 59 117

Instead of doing a matrix multiply, we can multiply the corresponding elements of


two matrices or vectors using the .* operator.
C = A .* B
C =
1 4 0
4 25 -10
0 -10 1

Let's find the inverse of a matrix ...


X = inv(A)
X =
5 2 -2
-2 -1 1
0 -2 1

... and then illustrate the fact that a matrix times its inverse is the identity matrix.

I = inv(A) * A

I =
1 0 0
0 1 0
0 0 1

MATLAB has functions for nearly every type of common matrix calculation.

13 | P a g e
There are functions to obtain eigenvalues...
eig(A)
ans =
3.7321
0.2679
1.0000

To find determinant of any matrix determinant function can be used


For example det(A)will give the determinant of matrix A.
a = [ 1 2 3; 2 3 4; 1 2 5]
a =
1 2 3
2 3 4
1 2 5

det(a)

ans =
-2

You can concatenate two matrices to create a larger matrix. The pair of
square brackets '[]' is the concatenation operator.
MATLAB allows two types of concatenations:
1. Horizontal concatenation
2. Vertical concatenation
Example
Create a script file with the following code:
a = [ 10 12 23 ; 14 8 6; 27 8 9]
b = [ 12 31 45 ; 8 0 -9; 45 2 11]
c = [a, b]
d = [a; b]

When you run the file, it displays the following result:


a =
10 12 23
14 8 6
27 8 9
b =
12 31 45
8 0 -9
45 2 11
c =
10 12 23 12 31 45
14 8 6 8 0 -9
27 8 9 45 2 11

14 | P a g e
d =
10 12 23
14 8 6
27 8 9
12 31 45
8 0 -9
45 2 11

3.6 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 5thcolumn, of the
matrix a, as created in the last section, we type −
a =[12345;23456;34567;45678];
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 =[12345;23456;34567;45678];
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 =[12345;23456;34567;45678];
a(:,2:3)

MATLAB will execute the above statement and return the following result −
ans =
2 3
3 4
4 5
5 6

15 | P a g e
In the same way, you can create a sub-matrix taking a sub-part of a matrix.
a =[12345;23456;34567;45678];
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:
345
456

To do this, write −
a =[12345;23456;34567;45678];
sa= a(2:3,2:4)

MATLAB will execute the above statement and return the following result −
sa =
3 4 5
4 5 6

Now consider indexing into a matrix. We'll use a magic square for our experiments:
A = magic(4)
A =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
Most often, indexing in matrices is done using two subscripts—one for the rows and
one for the columns. The simplest form just picks out a single element:
A(2,4) % Extract the element in row 2, column 4
ans =
8
More generally, one or both of the row and column subscripts can be vectors:
A(2:4,1:2)
ans =
5 11
9 7
4 14
A single : in a subscript position is shorthand notation for 1:end and is often used to
select entire rows or columns:
A(3,:) % Extract third row
ans =
9 7 6 12

16 | P a g e
A(:,end) % Extract last column
ans =
13
8
12
1
There is often confusion over how to select scattered elements from a matrix.
For example, suppose you want to extract the (2,1), (3,2), and (4,4) elements from A.
The expression A([2 3 4], [1 2 4])won't do what you want. This diagram illustrates how
two-subscript indexing works:

3.7 Linear Indexing


What does this expression A(14) do?
When you index into the matrix A using only one subscript, MATLAB treats A as if its
elements were strung out in a long column vector, by going down the columns
consecutively, as in:
16
5
9
...
8
12
1
The expression A(14) simply extracts the 14th element of the implicit column
vector. Indexing into a matrix with a single subscript in this way is often called linear
indexing.
Here are the elements of the matrix A along with their linear indices:

17 | P a g e
The linear index of each element is shown in the upper left.
From the diagram you can see that A(14) is the same as A(2,4).
The single subscript can be a vector containing more than one linear index, as in:
A([6 12 15])
ans =
11 15 12
Consider again the problem of extracting just the (2,1), (3,2), and (4,4) elements of A.
You can use linear indexing to extract those elements:
A([2 7 16])
ans =
5 7 1

3.8 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 =[12345;23456;34567;45678];
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

18 | P a g e
Next, let us delete the fifth column of a −

a =[12345;23456;34567;45678];
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
3.8.1 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 =[123;456;789];
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

19 | P a g e
CHAPTER - 4
MATLAB - Decision Making
4.1 If-else statements
Following is the general form of a typical decision making structure found in most of
the programming languages −

MATLAB provides following types of decision making statements.


Statement Description
if ... end statement An if ... end statement consists of a boolean expression
followed by one or more statements.
if...else...end statement An if statement can be followed by an optional else
statement, which executes when the boolean expression is
false.
If... An if statement can be followed by one (or more)
elseif...elseif...else...end optional elseif... and an else statement, which is very useful
statements to test various conditions.
nested if statements You can use one if or elseif statement inside
another if or elseif statement(s).
switch statement A switch statement allows a variable to be tested for equality
against a list of values.
nested switch You can use one switch statement inside
statements another switch statement(s).

20 | P a g e
Example
a = 10;
% check the condition using if statement
if a < 20
% if condition is true then print the following
fprintf('a is less than 20\n' );
end
fprintf('value of a is : %d\n', a);

When you run the file, it displays the following result:


a is less than 20
value of a is : 10

4.2 Loops
A loop statement allows us to execute a statement or group of statements multiple
times and following is the general form of a loop statement in most of the
programming languages −

MATLAB provides following types of loops to handle looping requirements. Click the
following links to check their detail −
Loop Type Description
while loop Repeats a statement or group of statements while a
given condition is true. It tests the condition before
executing the loop body.
for loop Executes a sequence of statements multiple times and
abbreviates the code that manages the loop variable.
nested loops You can use one or more loops inside any another loop.

21 | P a g e
4.2.1 For Loop
A for loop is a repetition control structure that allows you to efficiently write a loop
that needs to execute a specific number of times.

for a =10:20
fprintf('value of a: %d\n', a);
end

When you run the file, it displays the following result:


value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20

4.2.2 While Loop


The while loop repeatedly executes statements while condition is true
a =10;
%while loop execution
while( a <20)
fprintf('value of a: %d\n', a);
a = a +1;
end

When you run the file, it displays the following result:


value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

4.3 Loop Control Statements


Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope are
destroyed.

22 | P a g e
MATLAB supports the following control statements.
Control Statement Description
break statement Terminates the loop statement and transfers execution
to the statement immediately following the loop.
continue statement Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.

Example of break statement


a = 10;
% while loop execution
while (a < 20 )
fprintf('value of a: %d\n', a);
a = a+1;
if( a > 15)
% terminate the loop using break statement
break;
end
end
When you run the file, it displays the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
Example of Continue statement
a = 10;
%while loop execution
while a < 20
if a == 15
% skip the iteration
a = a + 1;
continue;
end
fprintf('value of a: %d\n', a);
a = a + 1;
end
When you run the file, it displays the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

23 | P a g e
CHAPTER - 5 MATLAB – Plotting
5.1 Graph Plotting Commands
Command Purpose
Axis Sets axis limits.
Grid Displays gridlines.
Plot Generates xy plot.
print Prints plot or saves plot to a file.
title Puts text at top of plot.
xlabel Adds text label to x-axis.
ylabel Adds text label to y-axis.
close Closes the current plot.
close all Closes all plots.
figure Opens a new figure window.
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 sub windows.
text Places string in figure.
bar Creates bar chart.
loglog Creates log-log plot.
polar Creates polar plot.
semilogx Creates semi log plot. (Logarithmic abscissa).
semilogy Creates semi log plot. (Logarithmic ordinate).
stairs Creates stairs plot.
stem Creates stem plot.
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 −

24 | P a g e
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.
Create a script file and type the following code −
x =[12345678910];
x =[-100:20:100];
y = x.^2;
plot(x, y)

When you run the file, MATLAB displays the following plot −

25 | P a g e
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 −

5.2 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.
 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.
5.2.1 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 −

26 | P a g e
5.3 Drawing Multiple Functions on the Same Graph
You can draw multiple graphs on the same plot. The following example
demonstrates the concept −
5.3.1 Example
Create a script file and type the following code −
x =[0:0.01:10];
y = sin(x);
g =cos(x);
plot(x, y, x, g,'.-'), legend('Sin(x)','Cos(x)')
MATLAB generates the following graph −

27 | P a g e
5.4 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

5.4.1 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')

28 | P a g e
When you run the file, MATLAB generates the following graph −

5.5 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([xminxmaxyminymax])

The following example shows this −


5.5.1 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([010-11])

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

29 | P a g e
5.6 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 p specifies where to put a particular plot.
Each plot created with the subplot command can have its own characteristics.
Following example demonstrates the concept –
5.6.1 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([05-11])
y =exp(-2*x).*sin(10*x);
subplot(1,2,2)
plot(x,y),xlabel('x'),ylabel('exp(–2x)*sin(10x)'),axis([05-11])

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

30 | P a g e
CHAPTER - 6 MATLAB – Graphics
This chapter will continue exploring the plotting and graphics capabilities of MATLAB.
We will discuss −
 Drawing bar charts
 Drawing contours
 Three dimensional plots

6.1 Drawing Bar Charts


The bar command draws a two dimensional bar chart. Let us take up an example to
demonstrate the idea.
6.1.1 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-depsgraph.eps

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

31 | P a g e
6.2 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.
6.2.1 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;%ourfunction
contour(x,y,g)% call the contour function
print-depsgraph.eps

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

32 | P a g e
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;%ourfunction
[C, h]= contour(x,y,g);% call the contour function
set(h,'ShowText','on','TextStep',get(h,'LevelStep')*2)
print-depsgraph.eps

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

6.3 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.
The following example demonstrates the concept −
6.3.1 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-depsgraph.eps

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

33 | P a g e
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.

34 | P a g e
CHAPTER - 7 MATLAB – Functions
A function is a group of statements that together perform a task. In MATLAB,
functions are defined in separate files. The name of the file and of the function should
be the same.
Functions operate on variables within their own workspace, which is also called
the local workspace, separate from the workspace you access at the MATLAB
command prompt which is called the base workspace.
Functions can accept more than one input arguments and may return more than one
output arguments.
Syntax of a function statement is –

function[out1,out2,...,outN]=myfun(in1,in2,in3,...,inN)

7.1 Example
The following function named mymax should be written in a file
named mymax.m. It takes five numbers as argument and returns the maximum of
the numbers.
Create a function file, named mymax.m and type the following code in it −
function max =mymax(n1, n2, n3, n4, n5)
%Thisfunction calculates the maximum of the
% five numbers given as input
max= n1;
if(n2 > max)
max= n2;
end
if(n3 > max)
max= n3;
end
if(n4 > max)
max= n4;
end
if(n5 > max)
max= n5;
end

The first line of a function starts with the keyword function. It gives the name
of the function and order of arguments. In our example, the mymax function has five
input arguments and one output argument.
The comment lines that come right after the function statement provide the
help text. These lines are printed when you type −
helpmymax

35 | P a g e
MATLAB will execute the above statement and return the following result −
This function calculates the maximum of the
five numbers given as input

You can call the function as −


mymax(34,78,89,23,11)

MATLAB will execute the above statement and return the following result −
ans = 89

7.2 Anonymous Functions


An anonymous function is like an inline function in traditional programming
languages, defined within a single MATLAB statement. It consists of a single MATLAB
expression and any number of input and output arguments.
You can define an anonymous function right at the MATLAB command line or within
a function or script.
This way you can create simple functions without having to create a file for them.
The syntax for creating an anonymous function from an expression is
f =@(arglist)expression
7.2.1 Example
In this example, we will write an anonymous function named power, which
will take two numbers as input and return first number raised to the power of the
second number.
Create a script file and type the following code in it −
power=@(x, n)x.^n;
result1 =power(7,3)
result2 =power(49,0.5)
result3 =power(10,-10)
result4 = power (4.5,1.5)
When you run the file, it displays −
result1 = 343
result2 = 7
result3 = 1.0000e-10
result4 = 9.5459

7.3 Primary and Sub-Functions


Any function other than an anonymous function must be defined within a file.
Each function file contains a required primary function that appears first and any
number of optional sub-functions that comes after the primary function and used by
it.

36 | P a g e
Primary functions can be called from outside of the file that defines them,
either from command line or from other functions, but sub-functions cannot be called
from command line or other functions, outside the function file.
Sub-functions are visible only to the primary function and other sub-functions
within the function file that defines them.
7.3.1 Example
Let us write a function named quadratic that would calculate the roots of a
quadratic equation. The function would take three inputs, the quadratic co-efficient,
the linear co-efficient and the constant term. It would return the roots.
The function file quadratic.m will contain the primary function quadratic and the sub-
function disc, which calculates the discriminant.
Create a function file quadratic.m and type the following code in it −
function[x1,x2]= quadratic(a,b,c)
%thisfunction returns the roots of
% a quadratic equation.
%It takes 3 input arguments
% which are the co-efficients of x2, x and the
%constant term
%It returns the roots
d =disc(a,b,c);
x1=(-b + d)/(2*a);
x2=(-b - d)/(2*a);
end%end of quadratic

function dis = disc(a,b,c)


%function calculates the discriminant
dis=sqrt(b^2-4*a*c);
end%end of sub-function

You can call the above function from command prompt as −


quadratic(2,4,-4)

MATLAB will execute the above statement and return the following result −
ans = 0.7321

7.4 Nested Functions


You can define functions within the body of another function. These are called
nested functions. A nested function contains any or all of the components of any
other function.
Nested functions are defined within the scope of another function and they share
access to the containing function's workspace.
A nested function follows the following syntax −
function x = A(p1, p2)
...

37 | P a g e
B(p2)
function y = B(p3)
...
end
...
end
7.4.1 Example
Let us rewrite the function quadratic, from previous example, however, this
time the disc function will be a nested function.
Create a function file quadratic2.m and type the following code in it −
function[x1,x2]= quadratic2(a,b,c)
function disc % nested function
d =sqrt(b^2-4*a*c);
end%end of function disc
disc;
x1=(-b + d)/(2*a);
x2=(-b - d)/(2*a);
end%end of function quadratic2
You can call the above function from command prompt as −

quadratic2(2,4,-4)
MATLAB will execute the above statement and return the following result −
ans = 0.73205

7.5 Private Functions


A private function is a primary function that is visible only to a limited group of
other functions. If you do not want to expose the implementation of a function(s),
you can create them as private functions.
Private functions reside in subfolders with the special name private.
They are visible only to functions in the parent folder.
7.5.1 Example
Let us rewrite the quadratic function. This time, however, the disc function
calculating the discriminant, will be a private function.
Create a subfolder named private in working directory. Store the following function
file disc.m in it −
function dis = disc(a,b,c)
%function calculates the discriminant
dis=sqrt(b^2-4*a*c);
end%end of sub-function
Create a function quadratic3.m in your working directory and type the following code
in it −
function[x1,x2]= quadratic3(a,b,c)
%thisfunction returns the roots of
% a quadratic equation.

38 | P a g e
%It takes 3 input arguments
% which are the co-efficient of x2, x and the
%constant term
%It returns the roots
d =disc(a,b,c);
x1=(-b + d)/(2*a);
x2=(-b - d)/(2*a);
end%end of quadratic3
You can call the above function from command prompt as −
Quadra c3(2,4,-4)
MATLAB will execute the above statement and return the following result −
ans = 0.73205

7.6 Global Variables


Global variables can be shared by more than one function. For this, you need
to declare the variable as global in all the functions.
If you want to access that variable from the base workspace, then declare the
variable at the command line.
The global declaration must occur before the variable is actually used in a
function. It is a good practice to use capital letters for the names of global variables
to distinguish them from other variables.
7.6.1 Example
Let us create a function file named average.m and type the following code in it −
functionavg= average(nums)
global TOTAL
avg= sum(nums)/TOTAL;
end
Create a script file and type the following code in it −
global TOTAL;
TOTAL =10;
n =[34,45,25,45,33,19,40,34,38,42];
av= average(n)
When you run the file, it will display the following result −
av = 35.500

39 | P a g e

You might also like