Page 1
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Fundamentals of MATLABFundamentals of MATLABDelivered byDelivered by
Dr. Suman ChakrabortyDr. Suman ChakrabortyProfessorProfessor
Department of Mechanical EngineeringDepartment of Mechanical EngineeringIIT KharagpurIIT Kharagpur
Page 2
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
OutlineOutline
• Introduction – Using MATLAB• Basics of Programming• Introduction to 2D and 3D plot• Statistical Analysis• Numerical Analysis• Symbolic Mathematics• Conclusion
Page 3
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
What is MATLABWhat 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
Page 4
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
More about MATLABMore about MATLAB
• High-performance language for technical computing
• Integrates computation, visualization, and programming in an easy-to-use user environment
Page 5
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Uses of MATLABUses 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
Page 6
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Components of MATLABComponents of MATLAB
• Basic Window• Extensive Help• GUI• Toolboxes• SIMULINK
Page 7
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
ToolboxesToolboxes
Control System Communications Financial Fuzzy Logic
Image Processing Neural Network PDE Signal Processing
Statistics Symbolic Math
And Many More …
Page 8
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
SimulinkSimulink
• Simulink Extensions– Simulink Accelerator– Real-Time Workshop– Stateflow
• Blocksets– DSP– Nonlinear Control Design– Communications– Fixed-Point
Page 9
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Documentation SetDocumentation 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
Page 10
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Basic WindowBasic Window
Command line
ResultVisualization
File Management
WorkingVariables
CommandHistory
MenuWorking Directory
Page 11
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Help and DemoHelp and DemoAccess Matlab Help Menu
OrType help in Command Window
Type help subtopic
Access Matlab Demo Menu Or
Type demo in Command Window
Page 12
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Basics of ProgrammingBasics of Programming
Page 13
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
File TypesFile Types
• .m filesScript (executable program)Function (user written function)
• .fig files Plot visualization and manipulation
• .dat or .mat files
Working with Formatted Data
Page 14
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Script and Function FilesScript and Function FilesScript Files Function Files
ParameterAssignment
StatementEvaluation
Function Declaration on topSyntax: function [output parameters] = function name (input parameters)
Save the file in – function name.m
Page 15
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
VariablesVariablesMATLAB 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 VariablesVector Variables
MatricesStrings
Page 16
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Creating and Operating with Creating and Operating with VariablesVariables
Scalar Vector
Strings
# variable with one row and one column
>> x = 2;>> y = 3;
>> z = x + y;>> w = y – x;>> u = y*x;
# 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
>> sFirst = ‘Hello’>> sSecond = ‘All’
>> sTotal = [sFirst, ‘ ’, sSecond]
Page 17
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Handling MatricesHandling MatricesInitialization Transpose
Multiplication
Inverse
Determinant Eigenvalues
Page 18
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
OperatorsOperators
Arithmetic operatorsPlus + 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
Relational operators
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 xor
Page 19
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
CONTROL FLOW STATEMENTSCONTROL FLOW STATEMENTS
“for” Loopfor 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
Page 20
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
“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
WHILE STATEMENTSWHILE STATEMENTS
Page 21
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
“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
IF-ELSE STATEMENTSIF-ELSE STATEMENTS
Page 22
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Debugging MATLABDebugging 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: 16Assignment 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”
Page 23
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Introduction to 2D and 3D plotIntroduction to 2D and 3D plot
Page 24
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Plots Using MATLABPlots Using MATLAB
• 2-D Graphics
• 3-D Graphics
Page 25
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Example: Plot y = sin x in 0 ≤ x ≤ 2π 2-D Graphics2-D Graphics
Page 26
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Command Line PlottingCommand Line Plotting
Page 27
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Editing FiguresEditing Figures
Edit Button
Legend
Text
Axis Label
Line or Point Type
Page 28
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Command Line EditingCommand Line Editing
Page 29
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Plot in Polar Co-ordinatePlot in Polar Co-ordinate
Page 30
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Fitting PolynomialsFitting Polynomials
Page 31
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Data StatisticsData Statistics
Page 32
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Plotting polynomialsPlotting polynomialsy = x3 + 4x2 - 7x – 10 in 1 ≤ x ≤ 3
Page 33
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Specialized Plots using MATLABSpecialized Plots using MATLAB
• Bar and Area Graphs• Pie Charts• Histograms• Discrete Data Graphs
Page 34
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Bar and Area PlotsBar and Area Plots
Page 35
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Pie ChartsPie Charts
Page 36
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
HistogramsHistograms
Page 37
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Discrete Data GraphsDiscrete Data Graphs
Page 38
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
3-D Graphics3-D GraphicsUse “plot3” in place of “plot” : Simple Enough !!!!
Page 39
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Use of “Mesh”, “Surf”, “Contour”Use of “Mesh”, “Surf”, “Contour”
Page 40
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Statistical AnalysisStatistical Analysis
Page 41
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Data Import in MATLABData 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
Page 42
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Other methods of ImportOther methods of Import
• Specialized file reader function– dlmread Read ASCII data file– imread Read image from graphics file– wk1read Read spreadsheet (WK1) file– auread Read Sun (.au) sound file– wavread Read Microsoft WAVE (.wav) sound file– readsnd Read SND resources and files (Macintosh)
• MEX-file to read the data• Develop an associated Fortran or C
program
Page 43
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Exporting Data from MATLABExporting 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
Page 44
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Specialized Write FunctionsSpecialized Write Functions
• dlmwrite Write ASCII data file• wk1write Write spreadsheet (WK1) file• imwrite Write image to graphics file• auwrite Write Sun (.au) sound file• wavwrite Write Microsoft WAVE (.wav) sound file• writesnd Write SND resources and files
(Macintosh)
Page 45
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Data StatisticsData Statistics
• Basic functions for data statistics:– max Largest component– min Smallest component– mean Average or mean value– median Median value– std Standard deviation– sort Sort in ascending order– sortrows Sort rows in ascending order– sum Sum of elements
Page 46
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
More Statistical FunctionsMore Statistical Functions
– prod Product of elements.– diff Difference function and
approximate derivative– trapz Trapezoidal numerical
integration– cumsum Cumulative sum of elements– cumprod Cumulative product of elements– cumtrapz Cumulative trapezoidal numerical
integration
Page 47
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Covariance and CorrelationCovariance 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
Page 48
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Minimizing FunctionsMinimizing 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
Page 49
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Plotting Mathematical FunctionsPlotting Mathematical Functions
fplot('humps',[-3,3])
Page 50
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Numerical AnalysisNumerical Analysis
Page 51
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Functions for Finite DifferencesFunctions for Finite Differences
• diff Difference between successive elements of a vector
Numerical partial derivatives of a vector
• gradient Numerical partial derivatives a matrix
• del2 Discrete Laplacian of a matrix
Page 52
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Functions for Fourier AnalysisFunctions for Fourier Analysis
• fft Discrete Fourier transform• fft2 Two-dimensional discrete Fourier
transform• fftn N-dimensional discrete Fourier transform.• ifft Inverse discrete Fourier transform• ifft2 Two-dimensional inverse discrete Fourier
transform• ifftn N-dimensional inverse discrete Fourier
transform• abs Magnitude• angle Phase angle
Page 53
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Solving Linear EquationsSolving 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\ASystem is solved by ‘backslash’ operator
Page 54
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Overdetermined EquationOverdetermined Equation
With a, b dataset fitting equation is predicted asaeccab 21)(
MATLAB finds C1 = 0.4763 and C2 = 0.3400
Page 55
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Undetermined EquationUndetermined 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
Page 56
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Ordinary Differential EquationsOrdinary 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
Page 57
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Generic Syntax for ODE SolverGeneric 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 pointsY Solution array. Each row in Y corresponds to the solution at a
time returned in the corresponding row of T
Page 58
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Numerical IntegrationNumerical 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 Simpson’s Rule• quad8 - Adaptive Newton Cotes 8
panel rule
Page 59
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Numerical Integration - Example
>> Q = quad (‘sin’,0,2*pi)>> Q = 0
Page 60
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Performing Double IntegralPerforming 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
Page 61
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Symbolic MathematicsSymbolic Mathematics
Page 62
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Symbolic MathematicsSymbolic Mathematics
• The Symbolic Math Toolboxes include symbolic computation into MATLAB’s numeric environment
• Facilities Available with Symbolic Math Toolboxes contain – Calculus, Linear Algebra, Simplification, Solution of Equations, Variable-Precision Arithmetic, Transforms and Special Applied Functions
Page 63
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
DemonstrationsDemonstrationsCommand Line Demonstrations are available
with Symbolic Math Toolboxes
Page 64
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Example: DifferentiationExample: 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
Page 65
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
In Summary - Why MATLAB !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
Page 66
MATLAB orientation course: MATLAB orientation course: Organized byOrganized by FOCUS – R&D FOCUS – R&D
Thank YouThank You