Fundamentals of MATLAB
Delivered by
Dr. Suman Chakraborty
Professor
Department of Mechanical Engineering
IIT Kharagpur
MATLAB orientation course: Organized by FOCUS R&D
Outline
Introduction Using MATLAB
Basics of Programming
Introduction to 2D and 3D plot
Statistical Analysis
Numerical Analysis
Symbolic Mathematics
Conclusion
MATLAB orientation course: Organized by FOCUS R&D
What is MATLAB
matrix laboratory
Was originally written to provide easy
access to matrix software developed by
the LINPACK and EISPACK projects that
together presented the state-of-the-art
software for matrix manipulation
Standard instructional tool for industrial
optimization and advance computations in
mathematics, engineering, and science
MATLAB orientation course: Organized by FOCUS R&D
More about MATLAB
High-performance language for technical
computing
Integrates computation, visualization, and
programming in an easy-to-use user
environment
MATLAB orientation course: Organized by FOCUS R&D
Uses of MATLAB
Math and computation
Algorithm development
Application development, including
graphical user interface (GUI) building
Data analysis, exploration, and
visualization
Modeling, simulation, and prototyping
Scientific and engineering graphics
MATLAB orientation course: Organized by FOCUS R&D
Components of MATLAB
Basic Window
Extensive Help
GUI
Toolboxes
SIMULINK
MATLAB orientation course: Organized by FOCUS R&D
Toolboxes
Control System
Financial
Image Processing
PDE
Statistics
Communications
Fuzzy Logic
Neural Network
Signal Processing
Symbolic Math
And Many More
MATLAB orientation course: Organized by FOCUS R&D
Simulink
Simulink Extensions
Simulink Accelerator
Real-Time Workshop
Stateflow
Blocksets
DSP
Nonlinear Control Design
Communications
Fixed-Point
MATLAB orientation course: Organized by FOCUS R&D
Documentation Set
MATLAB incorporates an exclusive set of online help
and function references containing following
divisions
MATLAB Installation Guide
Getting Started with MATLAB
Using MATLAB
Using MATLAB Graphics
The MATLAB Application Program Interface Guide
New features guide
MATLAB orientation course: Organized by FOCUS R&D
Basic Window
Menu
Working Directory
Command line
File
Management
Result
Visualization
Working
Variables
Command
History
MATLAB orientation course: Organized by FOCUS R&D
Help and Demo
Access Matlab Help Menu
Or
Type help in Command Window
Access Matlab Demo Menu
Or
Type demo in Command Window
Type help subtopic
MATLAB orientation course: Organized by FOCUS R&D
Basics of Programming
MATLAB orientation course: Organized by FOCUS R&D
File Types
.m files
Script (executable program)
Function (user written function)
.fig files
Plot visualization and
manipulation
.dat or
.mat files
Working with Formatted
Data
MATLAB orientation course: Organized by FOCUS R&D
Script and Function Files
Script Files
Function Files
Parameter
Assignment
Save the file in function name.m
Statement
Evaluation
Function Declaration on top
Syntax: function [output parameters] = function name (input parameters)
MATLAB orientation course: Organized by FOCUS R&D
Variables
MATLAB variables are created when they appear
on the left of an equal sign. The general
statement
>> variable = expression
creates the variable and assigns to it the value
of the expression on the right hand side
||Types of variables||
Scalar Variables
Vector Variables
Matrices
Strings
MATLAB orientation course: Organized by FOCUS R&D
Creating and Operating with
Variables
Vector
# variable with many rows
and columns
>> x = zeros(4,2);
>> y = ones(6,8);
>> x(1,3) = 1729;
>> x(:,1) = [0 0 0 0]
Colon Notation
Scalar
# variable with one row
and one column
>> x = 2;
>> y = 3;
>> z = x + y;
>> w = y x;
>> u = y*x;
Strings
>> sFirst = Hello
>> sSecond = All
>> sTotal = [sFirst, , sSecond]
MATLAB orientation course: Organized by FOCUS R&D
Handling Matrices
Initialization
Transpose
Inverse
Multiplication
Determinant
Eigenvalues
MATLAB orientation course: Organized by FOCUS R&D
Operators
Relational operators
Arithmetic operators
Plus
Minus
Matrix multiply
Array multiply
Matrix power
Array power
Backslash or left matrix divide
Slash or right matrix divide
Left array divide
Right array divide
Kronecker tensor product
+
*
.*
^
.^
\
/
.\
./
kron
Equal
==
Not equal
~=
Less than
< Greater
than
>
Less than or equal
<=
Greater than or equal >=
Logical operators
Short-circuit logical AND
Short-circuit logical OR
Element-wise logical AND
Element-wise logical OR
Logical NOT
Logical EXCLUSIVE OR
MATLAB orientation course: Organized by FOCUS R&D
&&
||
&
|
~
xor
CONTROL FLOW STATEMENTS
for Loop
for n=1:3
% Starting value=1, end=3, increment=1
for m=3:-1:1
% Starting value=3, end=3, increment= -1
a(n,m) = n.^2 + m.^2;
end
% End of the for loop of m
end
% End of the for loop of n
Output
2 5 10
a = 5 8 13
10 13 18
MATLAB orientation course: Organized by FOCUS R&D
WHILE STATEMENTS
while Loop
n = 0; eps = 1;
while (1+eps) > 1
eps = eps/2;
n = n + 1; % n indicates how many times the loop is
executed
end
OUTPUT
n = 53
MATLAB orientation course: Organized by FOCUS R&D
IF-ELSE STATEMENTS
if-else Statement
rt = 1:4; pp=0; qq=0;
for i=1:4
if (rt(i) < 2)
pp = pp + 1; % Indicates how many times if executed
else
qq = qq + 1; % Indicates how many times else executed
end
% End of if-else statement
end
% End of for Loop
OUTPUT
pp = 1
qq = 3
MATLAB orientation course: Organized by FOCUS R&D
Debugging MATLAB
Syntax Error
e.g. a function has been misspelled or a parenthesis
has been omitted
Display error message and line number
??? Error: File: D:\MATLAB6p5\work\DNA melting langevin\HeteroSeq1.m
Line: 17 Column: 16
Assignment statements do not produce results. (Use == to test for
equality.)
Run-time Error
e.g. insertion of a wrong variable or a calculation has
been performed wrongly such as divided by zero or
NaN
MATLAB orientation course: Organized by FOCUS R&D
Introduction to 2D and 3D plot
MATLAB orientation course: Organized by FOCUS R&D
Plots Using MATLAB
2-D Graphics
3-D Graphics
MATLAB orientation course: Organized by FOCUS R&D
2-D Graphics
Example: Plot y = sin x in 0 x 2
MATLAB orientation course: Organized by FOCUS R&D
Command Line Plotting
MATLAB orientation course: Organized by FOCUS R&D
Editing Figures
Edit Button
Legend
Text
Line or Point Type
Axis Label
MATLAB orientation course: Organized by FOCUS R&D
Command Line Editing
MATLAB orientation course: Organized by FOCUS R&D
Plot in Polar Co-ordinate
MATLAB orientation course: Organized by FOCUS R&D
Fitting Polynomials
MATLAB orientation course: Organized by FOCUS R&D
Data Statistics
MATLAB orientation course: Organized by FOCUS R&D
Plotting polynomials
y = x3 + 4x2 - 7x 10 in 1 x 3
MATLAB orientation course: Organized by FOCUS R&D
Specialized Plots using MATLAB
Bar and Area Graphs
Pie Charts
Histograms
Discrete Data Graphs
MATLAB orientation course: Organized by FOCUS R&D
Bar and Area Plots
MATLAB orientation course: Organized by FOCUS R&D
Pie Charts
MATLAB orientation course: Organized by FOCUS R&D
Histograms
MATLAB orientation course: Organized by FOCUS R&D
Discrete Data Graphs
MATLAB orientation course: Organized by FOCUS R&D
3-D Graphics
Use plot3 in place of plot : Simple Enough !!!!
MATLAB orientation course: Organized by FOCUS R&D
Use of Mesh, Surf, Contour
MATLAB orientation course: Organized by FOCUS R&D
Statistical Analysis
MATLAB orientation course: Organized by FOCUS R&D
Data Import in MATLAB
Data as explicit list of elements
e.g. [1 3 -5 5 7 10 5]
Create Data in M-file
Data editor can be utilized, more effective
than the first one
Load data from ASCII file
e.g. g = load(mydata.dat)
Read data using fopen, fread and
MATLAB file I/O functions
MATLAB orientation course: Organized by FOCUS R&D
Other methods of Import
Specialized file reader function
dlmread
imread
wk1read
auread
wavread
readsnd
Read ASCII data file
Read image from graphics file
Read spreadsheet (WK1) file
Read Sun (.au) sound file
Read Microsoft WAVE (.wav) sound file
Read SND resources and files (Macintosh)
MEX-file to read the data
Develop an associated Fortran or C
program
MATLAB orientation course: Organized by FOCUS R&D
Exporting Data from MATLAB
Diary Command
creates a diary of present MATLAB session in
a disk file (excluding graphics)
View and edit with any word processor
e.g. diary mysession.out
diary off
Save data in ASCII format
Write data in .mat file
MATLAB orientation course: Organized by FOCUS R&D
Specialized Write Functions
dlmwrite
wk1write
imwrite
auwrite
wavwrite
writesnd
Write ASCII data file
Write spreadsheet (WK1) file
Write image to graphics file
Write Sun (.au) sound file
Write Microsoft WAVE (.wav) sound file
Write SND resources and files (Macintosh)
MATLAB orientation course: Organized by FOCUS R&D
Data Statistics
Basic functions for data statistics:
max
min
mean
median
std
sort
sortrows
sum
Largest component
Smallest component
Average or mean value
Median value
Standard deviation
Sort in ascending order
Sort rows in ascending order
Sum of elements
MATLAB orientation course: Organized by FOCUS R&D
More Statistical Functions
prod
diff
trapz
cumsum
cumprod
cumtrapz
Product of elements.
Difference function and
approximate derivative
Trapezoidal numerical
integration
Cumulative sum of elements
Cumulative product of elements
Cumulative trapezoidal numerical
integration
MATLAB orientation course: Organized by FOCUS R&D
Covariance and Correlation
Function cov evaluates
Variance of a vector i.e. measure of spread or
dispersion of sample variable
Covariance of a matrix i.e. measure of
strength of linear relationships between
variables
Function corrcoef evaluates
correlation coefficient i.e. normalized
measure of linear relationship strength
between variables
MATLAB orientation course: Organized by FOCUS R&D
Minimizing Functions
Minimizing Functions with one variable
fmin (function name, range)
Minimizing Functions with several
variables
fmins (function name, starting vector)
Example:
>> a = fmin (humps,0.4,0.9)
>> a = 0.6370
MATLAB orientation course: Organized by FOCUS R&D
Plotting Mathematical Functions
fplot('humps',[-3,3])
MATLAB orientation course: Organized by FOCUS R&D
Numerical Analysis
MATLAB orientation course: Organized by FOCUS R&D
Functions for Finite Differences
diff
gradient
del2
Difference between
successive elements of a
vector
Numerical partial derivatives
of a vector
Numerical partial derivatives
a matrix
Discrete Laplacian of a
matrix
MATLAB orientation course: Organized by FOCUS R&D
Functions for Fourier Analysis
fft
fft2
fftn
ifft
ifft2
ifftn
abs
angle
Discrete Fourier transform
Two-dimensional discrete Fourier
transform
N-dimensional discrete Fourier transform.
Inverse discrete Fourier transform
Two-dimensional inverse discrete Fourier
transform
N-dimensional inverse discrete Fourier
transform
Magnitude
Phase angle
MATLAB orientation course: Organized by FOCUS R&D
Solving Linear Equations
Solution by Square System
Overdetermined System
Undetermined System
General situation involves a square coefficient
matrix A and a single right-hand side column
vector b.
e.g. Ax = b then solution: x = b\A
System is solved by backslash operator
MATLAB orientation course: Organized by FOCUS R&D
Overdetermined Equation
With a, b dataset fitting equation is predicted as
b(a) c1 c2 e a
MATLAB finds C1 = 0.4763 and C2 = 0.3400
MATLAB orientation course: Organized by FOCUS R&D
Undetermined Equation
More unknowns than equations
Solution is not unique
MATLAB finds a basic solution even it is
not unique
Associated constraints can not be coupled
to MATLAB
MATLAB orientation course: Organized by FOCUS R&D
Ordinary Differential Equations
Nonstiff solvers
ode23: an explicit Runge-Kutta (2,3) formula i.e.
Bogacki-Shampine pair
ode45: an explicit Runge-Kutta (4,5) formula i.e.
Dormand-Prince pair
ode113: Adams-Bashforth-Moulton PECE solver
Stiff solvers
ode15s, ode23s, ode23t and ode23tb
MATLAB orientation course: Organized by FOCUS R&D
Generic Syntax for ODE Solver
>> [T,Y] = solver (Func, tspan, y0);
'Func' String containing the name of the file
that contains the
system of ODEs
tspan Vector specifying the interval of integration. For a two-element
vector tspan = [t0 tfinal], the solver integrates from t0 to tfinal.
y0 Vector of initial conditions for the problem.
Output:
T Column vector of time points
Y Solution array. Each row in Y corresponds to the solution at a time
returned in the
corresponding row of T
MATLAB orientation course: Organized by FOCUS R&D
Numerical Integration
The area under a section of a function F(x)
can be evaluated by numerically
integrating F(x), a process known as
quadrature. The in-built MATLAB functions
for 1D quadrature are:
quad Adaptive Simpsons Rule
quad8 Adaptive Newton Cotes 8
panel rule
MATLAB orientation course: Organized by FOCUS R&D
Numerical Integration - Example
>> Q = quad (sin,0,2*pi)
>> Q = 0
MATLAB orientation course: Organized by FOCUS R&D
Performing Double Integral
% function declaration
>> function integrnd_out = integrnd (x,y)
>> integrnd_out = x*sin(x) + y*cos(y);
% Double Integral Evaluation
>> x_min = pi;
>> x_max = 2*pi;
>> y_min = 0;
>> y_max = pi;
>>
>> intg_result = dblquad (integrnd, x_min, x_max, y_min, y_max)
>> intg_result = -9.8698
MATLAB orientation course: Organized by FOCUS R&D
Symbolic Mathematics
MATLAB orientation course: Organized by FOCUS R&D
Symbolic Mathematics
The Symbolic Math Toolboxes include
symbolic computation into MATLABs
numeric environment
Facilities Available with Symbolic Math
Toolboxes contain Calculus, Linear
Algebra, Simplification, Solution of
Equations, Variable-Precision Arithmetic,
Transforms and Special Applied Functions
MATLAB orientation course: Organized by FOCUS R&D
Demonstrations
Command Line Demonstrations are available
with Symbolic Math Toolboxes
MATLAB orientation course: Organized by FOCUS R&D
Example: Differentiation
>> syms a x
>> fx = sin (a*x)
>> dfx = diff(fx)
>> dfx = cos (a*x)*a
% with respect to a
>> dfa = diff(fx, a)
>> dfa = cos (a*x)*x
MATLAB orientation course: Organized by FOCUS R&D
In Summary - Why MATLAB !
Interpreted language for numerical computation
Perform numerical calculations and visualize the
results without complicated and time exhaustive
programming
Good accuracy in numerical computing
Specially in-built with commands and subroutines
that are commonly used by mathematicians
Toolboxes to make advance scientific
computations easy to implement
MATLAB orientation course: Organized by FOCUS R&D
Thank You
MATLAB orientation course: Organized by FOCUS R&D