Dr.M.Sushanth Babu - Matlab Hand Book
Dr.M.Sushanth Babu - Matlab Hand Book
Dr.M.Sushanth Babu - Matlab Hand Book
HAND BOOK
FOR
Undergraduate Students
By
Dr.M.Sushanth Babu
Professor
Department of Electronics and
Communication Engineering
MATLAB's Power of Computational Mathematics
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
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:
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.
Command History - This panel shows or rerun 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.
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.
Adding Comments
The percent symbol (%) is used for indicating a comment line. For example,
x=9 % assign the value 9 to x
Commonly used Operators and Special Characters
MATLAB supports the following commonly used operators and special characters:
Operator Purpose
+ Plus; addition operator.
- Minus; subtraction operator.
* Scalar and matrix multiplication operator.
.* Array multiplication operator.
^ Scalar and matrix exponentiation operator.
.^ Array exponentiation operator.
\ Left-division operator.
/ Right-division operator.
.\ Array left-division operator.
./ Array right-division operator.
Colon; generates regularly spaced elements and represents
: an entire row or column.
Parentheses; encloses function arguments and array
() indices; overrides precedence.
[] Brackets; enclosures array elements.
. Decimal point.
… Ellipsis; line-continuation operator
, Comma; separates statements and elements in a row
; Semicolon; separates columns and suppresses display.
Percent sign; designates a comment and specifies
% formatting.
_ Quote sign and transpose operator.
._ Non-conjugated transpose operator.
= Assignment operator.
Special Variables and Constants
MATLAB supports the following special variables and constants:
Name Meaning
ans Most recent answer.
eps Accuracy of floating-point precision.
i,j The imaginary unit √-1.
Inf Infinity.
NaN Undefined numerical result (not a number).
pi The number π
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.
Creating Vectors
Row vectors are created by enclosing the set of elements in square brackets,
using space or comma to delimit the elements.
Column vectors are created by enclosing the set of elements in square
brackets, using semicolon (;) to delimit the elements.
Creating Matrices
A matrix is a two-dimensional array of numbers.
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.
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.
whos Lists current variables (long display).
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.
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:
The format function has the following forms used for numeric display:
Command Purpose
cat Concatenates arrays.
find Finds indices of nonzero elements.
length Computes number of elements.
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.
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.
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 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.
The M Files
MATLAB allows writing two kinds of program files:
Scripts - script files are program files with .m extension. In these files, you
write series of commands, which you want to execute together. Scripts do not
accept inputs and do not return any outputs. They operate on data in the
workspace.
Functions - functions files are also program files with .m extension. Functions
can accept inputs and return outputs. Internal variables are local to the function.
Function Purpose
Char Convert to character array (string)
int2str Convert integer data to string
mat2str Convert matrix to string
num2str Convert number to string
str2double Convert string to double-precision value
str2num Convert string to number
native2unicode Convert numeric bytes to Unicode characters
unicode2native Convert Unicode characters to numeric bytes
base2dec Convert base N number string to decimal number
bin2dec Convert binary number string to decimal number
dec2base Convert decimal to base N number in string
dec2bin Convert decimal to binary number in string
dec2hex Convert decimal to hexadecimal number in string
hex2dec Convert hexadecimal number string to decimal number
Convert hexadecimal number string to double-precision
hex2num number
Arithmetic Operators
MATLAB allows two different types of arithmetic operations:
Matrix arithmetic operations
Array arithmetic operations
Operator Description
+ Addition or unary plus.
- Subtraction or unary minus.
* Matrix multiplication.
.* Array multiplication.
/ Slash or matrix right division
./ Array right division
\ Backslash or matrix left division
.\ Array left division
^ Matrix power
.^ Array power
' Matrix transpose
.' Array transpose
Functions for Arithmetic Operations
Apart from the above-mentioned arithmetic operators, MATLAB provides the
following commands/functions used for similar purpose:
Function Description
uplus(a) Unary plus; increments by the amount a
plus (a,b) Plus; returns a + b
uminus(a) Unary minus; decrements by the amount a
minus(a, b) Minus; returns a - b
times(a, b) Array multiply; returns a.*b
mtimes(a, b) Matrix multiplication; returns a* b
rdivide(a, b) Right array division; returns a ./ b
ldivide(a, b) Left array division; returns a.\ b
mrdivide(A, B) Solve systems of linear equations xA = B for x
mldivide(A, B) Solve systems of linear equations Ax = B for x
power(a, b) Array power; returns a.^b
mpower(a, b) Matrix power; returns a ^ b
Cumulative product; returns an array of the same size as
cumprod(A) the array A containing the cumulative product.
cumprod(A, dim) Returns the cumulative product along dimension dim.
Cumulative sum; returns an array A containing the
cumsum(A) cumulative sum.
Returns the cumulative sum of the elements along
cumsum(A, dim) dimension dim.
Differences and approximate derivatives; calculates
diff(X) differences between adjacent elements of X.
Applies diff recursively n times, resulting in the nth
diff(X,n) difference.
It is the nth difference function calculated along the
diff(X,n,dim) dimension specified by scalar dim
Product of array elements; returns the product of the
prod(A) array elements of A.
prod(A,dim) Returns the products along dimension dim.
Multiplies in and returns an array in the class specified by
prod(___,datatype) datatype.
Sum of array elements; returns sums along different
sum(A) dimensions of an array.
Sums along the dimension of A specified by scalar
sum(A,dim) dim.
ceil(A) Round toward positive infinity
fix(A) Round toward zero
floor(A) Round toward negative infinity
idivide(a, b) Integer division with rounding option
a./b except that fractional quotients are rounded
idivide(a, b,'fix') toward zero to the nearest integers.
idivide(a, b, Fractional quotients are rounded to the nearest
'round') integers.
Fractional quotients are rounded toward negative
idivide(A, B, 'floor') infinity to the nearest integers.
Fractional quotients are rounded toward infinity to the
idivide(A, B, 'ceil') nearest integers.
mod (X,Y) Modulus after division
rem (X,Y) Remainder after division
round(X) Round to nearest integer
Relational Operators
The following table shows the relational operators available in MATLAB
Operator Description
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
~= Not equal to
Function Description
eq(a, b) Tests whether a is equal to b
ge(a, b) Tests whether a is greater than or equal to b
gt(a, b) Tests whether a is greater than b
le(a, b) Tests whether a is less than or equal to b
lt(a, b) Tests whether a is less than b
ne(a, b) Tests whether a is not equal to b
isequal Tests arrays for equality
isequaln Tests arrays for equality, treating NaN values as equal
Functions for Logical Operations
MATLAB provides the following commands or functions used for the same
purpose
Function Description
and(A, B) Finds logical AND of array or scalar inputs
not(A) Finds logical NOT of array or scalar input
or(A, B) Finds logical OR of array or scalar inputs
xor(A, B) Logical exclusive-OR
Determine if all array elements of array A are
all(A) nonzero or true
Tests along the dimension of A specified by
all(A, dim) scalar dim
any(A) Determine if any array elements are nonzero
Tests along the dimension of A specified by
any(A,dim) scalar dim
False Logical 0 (false)
false(n) is an n-by-n matrix of logical zeros
false(m, n) is an m-by-n matrix of logical zeros
false(m, n, p, ...) is an m-by-n-by-p-by-... array of logical zeros
is an array of logical zeros that is the same size as
false(size(A)) array A.
is an array of logical zeros of the same data type
false(...,'like',p) and sparsity as the logical array p.
ind = find(X) Find indices and values of nonzero elements
logical(A) Convert numeric values to logical
True Logical 1 (true)
true(n) is an n-by-n matrix of logical ones
true(m, n) is an m-by-n matrix of logical ones
true(m, n, p, ...) is an m-by-n-by-p-by-... array of logical ones
is an array of logical ones that is the same size as
true(size(A)) array A
is an array of logical ones of the same data type
true(...,'like', p) and sparsity as the logical array p
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
bitset(a, pos) Set bit at specific location pos of a
Returns a shifted to the left by k bits, equivalent to
bitshift(a, k) multiplying by 2k
bitxor(a, b) Bit-wise XOR of integers a and b
swapbytes Swap byte ordering
Set Operations
The following table shows some commonly used set operations
Function Description
intersect(A,B) Set intersection of two arrays; returns the values
Treats each row of A and each row of B as single
intersect(A,B,'rows') entities and returns the rows common to both A and B
Returns an array the same size as A, containing
ismember(A,B) 1(true) where the elements of A are found in B
Treats each row of A and each row of B as single
ismember(A,B,'rows') entities and returns a vector containing 1 (true)
Returns logical 1 (true) if the elements of A are in
issorted(A) sorted order and logical 0 (false) otherwise
Returns logical 1 (true) if the rows of two-dimensional
matrix A are in sorted order, and logical 0 (false)
issorted(A, 'rows') otherwise
setdiff(A,B) Sets difference of two arrays
Treats each row of A and each row of B as single
setdiff(A,B,'rows') entities and returns the rows from A that are not in B
setxor Sets exclusive OR of two arrays
union Sets union of two arrays
unique Unique values in array
Matrix Operations
commonly used matrix operations:
Addition and Subtraction of Matrices
Division of Matrices
Scalar Operations of Matrices
Transpose of a Matrix
Concatenating Matrices
Matrix Multiplication
Determinant of a Matrix
Inverse of a Matrix
Special Arrays in MATLAB
The zeros() function creates an array of all zeros:
The ones() function creates an array of all ones:
The eye() function creates an identity matrix.
The rand() function creates an array of uniformly distributed random numbers
The magic() function creates a magic square array
We can also use the cat() function to build multidimensional arrays
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
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
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.
The following table describes its use for this purpose (let us have a matrix A):
Format Purpose
A(:,j) is the jth column of A.
A(i,:) is the ith row of A.
is the equivalent two-dimensional array. For matrices this is the
A(:,:) 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).
Function Purpose
Double Converts to double precision number
Single Converts to single precision number
int8 Converts to 8-bit signed integer
int16 Converts to 16-bit signed integer
int32 Converts to 32-bit signed integer
int64 Converts to 64-bit signed integer
uint8 Converts to 8-bit unsigned integer
uint16 Converts to 16-bit unsigned integer
uint32 Converts to 32-bit unsigned integer
uint64 Converts to 64-bit unsigned integer
String Functions in MATLAB
Following table provides brief description of the string functions in MATLAB
Function Purpose
blanks Create string of blank characters
Create cell array of strings from
cellstr character array
char Convert to character array (string)
Determine whether input is cell array
iscellstr of strings
Determine whether item is character
ischar array
sprintf Format data into string
strcat Concatenate strings horizontally
Join strings in cell array into single
strjoin string
Array elements that are alphabetic
letters
Array elements that are space
isspace characters
Determine whether string is of
isstrprop specified category
sscanf Read formatted data from string
strfind Find one string within another
strrep Find and replace substring
strsplit Split string at specified delimiter
strtok Selected parts of string
validatestring Check validity of text string
Determine symbolic variables in
symvar expression
Match regular expression (case
regexp sensitive)
Match regular expression (case
regexpi insensitive)
regexprep Replace string using regular expression
regexptranslate Translate string into regular expression
Importing Data
The importdata function allows loading various data files of different formats.
It has the following five forms:
Function Description
fclose Close one or all open files
feof Test for end-of-file
ferror Information about file I/O errors
fgetl Read line from file, removing newline characters
fgets Read line from file, keeping newline characters
fopen Open file, or obtain information about open files
fprintf Write data to text file
fread Read data from binary file
frewind Move file position indicator to beginning of open file
fscanf Read data from text file
fseek Move to specified position in file
ftell Position in open file
Write data to binary file
Import Text Data Files with Low-Level I/O
MATLAB provides the following functions for low-level import of text data files:
The fscanf function reads formatted data in a text or ASCII file.
The fgetl and fgets functions read one line of a file at a time, where a newline
character separates each line.
The fread function reads a stream of data at the byte or bit level.
Open the file with fopen function and get the file identifier.
Plotting:
Call the plot command, as plot(x, y)
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.
The subplot command is used for creating subplots
Code Colour
w White
k Black
b Blue
r Red
c Cyan
g Green
m Magenta
y Yellow
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)