7/29/2019 Training Program on MATLAB
1/48
Training Program on MATLAB
by
Dr. A.P. RuhilComputer Centre
7/29/2019 Training Program on MATLAB
2/48
Contents
Introduction to MATLAB
MATLAB Basics
MATLAB Programming Graphics & Animation
Applications
Statistical data analysis
7/29/2019 Training Program on MATLAB
3/48
Introduction to MATLAB
MATLAB (Matrix Laboratory) A special
purpose computer program to perform
optimized engineering and scientific
calculations.
Genesis: In 1960-70 a large number of
subroutines developed for specific
computational purpose in FORTRAN wereorganized into public domain packages for
free distribution.
7/29/2019 Training Program on MATLAB
4/48
MATLAB was originally created as a front
end for LINPACK A group of routines forworking with matrices and linear algebra.
Primary developer Prof. Cleve Moler
(Univ. of New Maxico) founded MathworkInc. to further develop and market the
product (MATLAB) commercially
Most widely used tools for highperformance numerical computations in
engineering and scientific departments.
7/29/2019 Training Program on MATLAB
5/48
Provide interactive working environmentwith hundred of built-in functions for
technical computation, graphics andanimation.
Built-in functions and Tool box: Linearalgebra, Statistical Data Analysis, SignalProcessing, Optimization, PartialDifferential Equations, Artificial NeuralNetwork, Fuzzy Logic, GA, Financial,
Communication, Symbolic Math, DataAcquisition, Database, Image processing,Compiler, External Interface etc.
7/29/2019 Training Program on MATLAB
6/48
Why MATLAB ?
Vector/matrix manipulation is intuitive
Plotting is easy and flexible Toolboxes for specialized functionality
Full programming language suitable for
quick prototyping
7/29/2019 Training Program on MATLAB
7/48
Advantages
Ease of use similar to Basic language
State of the art algorithms
Platform Independence
Predefined and user defined functions
Device Independent Plotting
Graphic User Interface for application
development Interface with C/ C++/ FORTRAN Languages
Matlab Compiler
7/29/2019 Training Program on MATLAB
8/48
Advantages of MATLAB
1-Ease of Use
MATLAB is similar to BASIC language.
Can be used as scratch pad to evaluate
expressions typed at the command line, or it canbe used to execute large prewritten programs.
Programs may be easily modified with the built-in integrated development environment and
debugged with the MATLAB debugger. As it is so easy to use, it is ideal for the rapid
prototyping of the programs.
7/29/2019 Training Program on MATLAB
9/48
2-Platform Independence
MATLAB is supported on many different
Computer systems, providing a large
measure of platform independence. Programs written on any platform will run
on all the other platforms.
7/29/2019 Training Program on MATLAB
10/48
3-Predefined Functions
MATLAB comes complete with anextensive library of functions that providetested and pre-packaged solutions to
many basic technical tasks. In addition to the large library of functions
built into the basic MATLAB language,many special-purpose toolboxes areavailable to help complex problems inspecific areas.
7/29/2019 Training Program on MATLAB
11/48
4-Device-Independent Plotting
MATLAB has many plotting and imaging
commands. The plots and images can be
displayed on any graphical output devicesupported by the computer on which
MATLAB is running. This capability makes
MATLAB an outstanding tool forvisualizing technical data.
7/29/2019 Training Program on MATLAB
12/48
5-Graphical User Interface
MATLAB includes tools that allow users to
interactively construct a graphical user
interface (GUI) for his or her program.With this capability, the users can design
sophisticated data analysis programs that
can be operated by relativelyinexperienced users.
7/29/2019 Training Program on MATLAB
13/48
6-MATLAB Compiler
MATLABs flexibility and platform
independence is achieved by compiling
MATLAB programs into a device-
independent p-code and then interpreting
the p-code instructions at runtime.
7-Interface with C/ C++/
FORTRAN Languages
7/29/2019 Training Program on MATLAB
14/48
Disadvantage
Slow in Interpreter mode
High Cost
7/29/2019 Training Program on MATLAB
15/48
MATLAB Environment
Fundamental data type is Array.
Scalar is also treated as array with one
row and one column
Three most Important windows are:
Command, Figure, Edit/Debug
Examples in Command window (run
MATLAB Environment)
7/29/2019 Training Program on MATLAB
16/48
MATLAB Desktop
Command Window
Launch Pad
History
Current Directory
7/29/2019 Training Program on MATLAB
17/48
Workspace is collection of all created
variables and arrays (who, whos, clear)
Getting Help:
? from menu or typing helpdesk
Type help followed by function name Type lookforfollowed by function/key word
Important Commands (clc, clear)
MATLAB Search Path
7/29/2019 Training Program on MATLAB
18/48
Variables
A variable is a holding place for a valuewhich can be given a name.
Variable Name Rules:
Must begin with a letter followed by anycombination of letters, numbers, and the
underscore.
Only first 31 characters are significant. Name must be unique.
Names are case sensitive
7/29/2019 Training Program on MATLAB
19/48
Double precision occupies 8 bytes or 64 bits
in size
Can hold integer, real, imaginary, or complex
values
Range: 10 ^ -308 to 10 ^ 308
15-16 significant decimal digits
Automatically created by assigning a numericvalue to a variable
V = 1 + I; (creates a complex number)
Numeric Variables
7/29/2019 Training Program on MATLAB
20/48
Consists of scalars or arrays of 16 bit values each
representing a single character
Automatically created by assigning a single character
or a character string to a variable Comment = This is a Character String; (creates a
1x26 character array)
Now show workspace window
Variables can be created at any time
Type of data assigned to variable determines
the type of variable
Character Variables
7/29/2019 Training Program on MATLAB
21/48
Initializing Variables
Assign data to the variables in an
assignment statement(var = expression)
Input data into the variable from Keyboardvar = input(Enter an input value: );
Read data from file
7/29/2019 Training Program on MATLAB
22/48
Useful Commands
who - shows the environment (name ofvariables in workspace)
clear- removes all variables from memory
clear v1 ez - removes variables v1 & ezfrom memory
clf- clears the current figure or graph
clc - clears the command window
Dir- lists current directory
delete fname - deletes file named fname
7/29/2019 Training Program on MATLAB
23/48
Special Values/ Variables
pi(3.14159)
inf infinity
NaN not a number clock current date and time
date current date
eps epsilon ans answer
7/29/2019 Training Program on MATLAB
24/48
Reserved Words
for
end
if
while
function
return elsif
case
otherwise
switch
continue else
try
catch
global persistent
break
MATLAB has some special (reserved)
words that may not be used.
7/29/2019 Training Program on MATLAB
25/48
Displaying Output data
Integer values are displayed as such
Real number up to four decimals
Very small or large number in scientificnotation with exponent
Default format can be changed to: format short 4 digits after decimal (default)
format long 14 digits after decimal
format short e, format short g
format long e, format long g
7/29/2019 Training Program on MATLAB
26/48
Save/ Load Data
MATLAB saves data in MAT file in a
special compact format. (default mode)
Use -ascii option to save data to exchange
data file other than MATLAB (use
extension as .dat)
Save filename var1 var2.
Load filename (to retrieve data from file)
7/29/2019 Training Program on MATLAB
27/48
MATLAB Basics
The fundamental unit of data (variable) in anyMATLAB program is the array. An array is acollection of data values organized into rowsand columns and known by a single name.
Arrays can be classified as either vector ormatrices. The term vector is usually used todescribe an array with only one dimension,
while the term matrix is usually used todescribe an array with two or moredimension.
7/29/2019 Training Program on MATLAB
28/48
MATLAB Matrices
MATLAB treats all variables as matrices.For our purposes a matrix can be thoughtof as an array, in fact, it is stored that way.
Vectors are special forms of matrices andcontain only one row OR one column.
Scalars are matrices with only one rowAND one column.
7/29/2019 Training Program on MATLAB
29/48
Multidimensional Array
2D
3D or more
Arrays are stored in memory in columnmajor order eg. For A(2x2) array elements
are stored as (1,1), (2,1), (1,2), (2,2)
Can be accessed as single array
subscription. Eg. A(3) will be A(1,2)
Subarray
7/29/2019 Training Program on MATLAB
30/48
MATLAB as Scratchpad
MATLAB can do everything a calculator
does
>> (1+4)*3
>> ans= 15
7/29/2019 Training Program on MATLAB
31/48
MATLAB Matrices (Scalar)
A matrix with only one row AND onecolumn is a scalar. A scalar can be
created in MATLAB as follows:
a_value=23 a_value =
23
>>area = pi*2.5^4;
>>x= 1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6;
7/29/2019 Training Program on MATLAB
32/48
Scalar Operations
Arithmetic Operations between tow
Scalars:
Addition: a + b
Subtraction: a b
Multiplication: a * b
Division: a / b
Exponentiation: a ^ b
Hierarchy: Parenthesis, ^, /, *, +, - from L to R
7/29/2019 Training Program on MATLAB
33/48
MATLAB Matrices (Row Vector)
A matrix with only one row is called a row
vector. A row vector can be created in
MATLAB as follows (note the commas):
rowvec= [12 14 63]
rowvec=
12 14 63
7/29/2019 Training Program on MATLAB
34/48
MATLAB Matrices (Col. Vector)
A matrix with only one column is called acolumn vector. A column vector can becreated in MATLAB as follows (note the
semicolons): colvec= [13; 45;2]
colvec=
1345
2
7/29/2019 Training Program on MATLAB
35/48
MATLAB Matrices
A matrix can be created in MATLAB as
follows (note the gaps AND semicolons):
matrix = [1 2 3; 4 5 6; 7 8 9]
matrix =
1 2 3
4 5 67 8 9
7/29/2019 Training Program on MATLAB
36/48
Extracting a Sub-Matrix
A portion of a matrix can be extracted and storedin a smaller matrix by specifying the names of
both matrices and the rows and columns to
extract. The syntax is: sub_matrix= matrix ( r1 : r2 , c1 : c2 );
where r1 and r2 specify the beginning and
ending rows and c1 and c2 specify thebeginning and ending columns to be extracted to
make the new matrix.
7/29/2019 Training Program on MATLAB
37/48
Array Operation
Performed between arrays on an element-
by-element basis
Array Addition: a + bArray Subtraction: a b
Array Multiplication: a .* b
Array Right Division: a ./ b
Array left Division: a .\ bArray Exponentiation: a .^ b
7/29/2019 Training Program on MATLAB
38/48
Follows the normal rules of linear algebra
such as matrix multiplication
Matrix Multiplication: a * b
Matrix Right Division: a / b %( a * inv(b) )
Matrix left Division: a \ b %( inv(a) * b)
Matrix Operation
7/29/2019 Training Program on MATLAB
39/48
MATLAB Symbols
. . . continue statement on next line
, separate statements and data
% start comment which ends at end ofline
; (1)suppress output
(2)used as a row separator in a matrix
: Specify range
7/29/2019 Training Program on MATLAB
40/48
Numeric Functions
sqrt(x) Calculates the square root of xmod(x, y) remainder or modulo function
exp(x) e raise to power x
log(x) natural logarithm base e
ceil(x) rounds x to nearest integer towards+ve infinity
fix(x) - rounds x to nearest integer towards Zero
floor(x) - rounds x to nearest integer towards -
ve infinityround(x) Rounds x to the nearest integer
Many more
7/29/2019 Training Program on MATLAB
41/48
Matrix Manipulation Function
Diag(x) Extract diagonal elements
Rot90(x) Rotate matrix 90 degree
tril(x) Extract lower triangular part
triu(x) Extract upper triangular partdet(x) Determinant of matrix
rank(x) - No. of linearly independent rows or
columns
trace(x) sum of diagonal elementseig(x) Eigenvalues and eigenvectors
Many more
7/29/2019 Training Program on MATLAB
42/48
Complex Variables
Complex number: c = a +bi
Complex variable is created by assigninga complex value
Operators:+ : for addition
- : for subtraction
* : for multiplication/ : for right division
\ : for left division
7/29/2019 Training Program on MATLAB
43/48
Functions for Complex Numbers
isreal(a)- returns 0 if a is complex number
abs(a) - returns magnitude of complex value
conj(a) -computes the complex conjugate
real(a) - returns the real portion
imag(a) - returns the imaginary portion
Angle(a)- returns the angle of complexnumber
7/29/2019 Training Program on MATLAB
44/48
Scientific problems always seem to involvethe solution of simultaneous linear
equations. For a few equations (two or
three at most) this may be done by hand.
For more than three equations it is
advisable to use a computer. MATLAB can
solve such equations easily.
For example: Solve for x1, x2, and x3satisfying:
Solution of Simultaneous Equations
7/29/2019 Training Program on MATLAB
45/48
For example: solve linear equations for x1,
x2, and x3
5x + 8y + 2z = 3
4x + 6y + 7z = 5
2x + 8y + 2z = 11
Solution:
a = [5 8 2; 4 6 7; 2 8 2];
b = [3; 5; 11];
X = [x; y; z];
X1 = a \ b;
7/29/2019 Training Program on MATLAB
46/48
MATLAB Graphics
MATLAB also provides a powerful set of
graphics commands to create and
manipulate graphics.
Many commands can be entered from the
Figure window.
Advanced commands must be enteredfrom the Command window or a script.
7/29/2019 Training Program on MATLAB
47/48
Simple Plots
plot(x,y)
For example:
x= 0:1:10;
y=x.^210.*x+15;
plot(x,y);
title (Plot of y=x.^2-10.*x+15)
xlabel(x) ylabel(y)
grid on
7/29/2019 Training Program on MATLAB
48/48
Multiple Graphs
It is possible to plot multiple functions on
the same graph. For Example:
x=0:0.1:6;y1 = sin(x);
y2 = cos(x)
plot(x,y1,'r--', x, y2, 'bo');