Mariusz Janiak p. 331 C-3, 71 320 26 44
2015 Mariusz Janiakc All Rights Reserved
1 Introduction
2 Matlab essentials
3 Matlab matrices
4 Control flow
5 Plotting
Matlab combines a desktop environment tuned for iterative analysis and design processes with a programming language that expresses matrix and array mathematics directly.1
Matlab stands for MATrix LABoratory Developed by Mathworks.
Computing and programming environment Programming language (script, JIT compiler) Multiplatform (Windows, Mac, Linux) Proprietary software (expensive) Web page
www.mathworks.com
1 The MathWorks, Inc.
Matlab in general
Professionally built (rigorously tested and fully documented) Interactive apps (off-the-shelf)
Ability to scale (clusters, GPUs and clouds)
Deploy to enterprise applications (production ready) Run on embedded devices (convert to C/C++ and HDL) Integrate with Model-Based Design (Simulink)
Typical Matlab domains Data Analytics Control Systems Robotics
Deep Learning Computer Vision Signal Processing
Wireless Communications
Quantitative Finance and Risk Management
Popular alternatives to Matlab
Octave (www.gnu.org/software/octave) Scilab (www.scilab.org)
Python + SciPy (www.scipy.org) SageMath (www.sagemath.org)
Matlab desktop
Main components
Command Window – the main window for executing commands (Matlab’s sandbox)
Workspace – display and manage a list of the currently defied variables (name, value, class)
Current Folder – file explorer, points the working directory Command History – display a list of the last commands entered (enable rerun)
Editor – advanced text editor for writing and running scripts and functions (debugger integrated)
Help Browser – extensive Matlab documentation (start here)
Matlab can be used interactively in the Command Window (interpreted environment)
Matlab can be used as a calculator Basic commands
who, whos – list current variables
clear – remove variable(s) from workspace
help – display help text (for specified functionality) doc– opens theHelp Browser
clc– clearCommand Window quit, exit – quit Matlab session
Ctrl+c interrupt a running program (eg. infinite loop)
Help facilities in principle contains all information about Matlab Use help to request info on a specific function.
h e l p ' f u n c t i o n n a m e '
It gives a short description of the function, the syntax, and other closely related help functions.
Use lookfor to find functions by keywords
l o o k f o r ' t o p i c '
It gives the list of all possible function names which contain the specific search word
Use doc to open the on-line version of the manual
d o c ' f u n c t i o n n a m e '
Matlab data types
2
2The MathWorks, Inc.
Variables
Created by using an assignment statement Weak dynamic typing
Have not to be previously declared (preallocate for speed) Identifier names
Must start with a letter followed by letters, digits, and underscores (without spaces),
Can contain up to namelengthmax (63) characters, Is case-sensitive
Should not be reserved word or name of a built-in variable/functions
Special variables and constants
ans– most recent answer (variable created automatically) eps– accuracy of floating-point precision
i, j – the imaginary unit √
−1 pi– the number π
inf, Inf – infinity
nan, Nan – undefined numerical result (not a number) realmin– largest finite floating point number
realmax– smallest positive normalized floating point number intmin– smallest integer value
intmax– largest positive integer value
Expressions is a legal combination of numerical values, mathematical operators, variables, and function calls
Long statements can be continued on to the next line by using ellipsis – three or more periods (...)
Semicolon (;)
indicates end of statement (in line multiple assignments) suppress and hide the Matlab output for an expression Comments
Percent (%) – comment line
Percent curly bracket (%{ %}) – block comments
The format command can be used to specify the output format of expressions (format short – default, scaled fixed point format with 5 digits)
Arithmetic operators
Symbol Role Info
+ Addition, unary plus plus, uplus - Subtraction, unary minus minus, uminus
* Matrix multiplication mtimes .* Element-wise multiplication times
/ Matrix right division mrdivide ./ Element-wise right division rdivide
\ Matrix left division mldivide .\ Element-wise left division ldivide
^ Matrix power mpower
.^ Element-wise power power
’ Complex conjugate transpose ctranspose
.’ Transpose transpose
Relational operators
Symbol Role Info
== Equal to eq
~= Not equal to ne
> Greater than gt
>= Greater than or equal to ge
< Less than lt
<= Less than or equal to le
Logical operators
Symbol Role Info
& Logical AND and
| Logical OR or
&& Logical AND (with short-circuiting)
|| Logical OR (with short-circuiting)
~ Logical NOT not
Special Characters
Symbol Name Role
@ At symbol Function handle construction and reference . Period or dot Decimal point
Element-wise operations Structure field access
Object property or method specifier ... Ellipsis Line continuation
, Comma Separator
: Colon Vector creation
Indexing For-loop iteration
; Semicolon Signify end of row Suppress output of code line ( ) Parentheses Operator precedence
Function argument enclosure Indexing
[ ] Square brackets Array construction Array concatenation
Empty matrix and array element deletion Multiple output argument assignment { } Curly brackets Cell array assignment and contents
Special Characters (cont.)
Symbol Name Role
% Percent Comment
Conversion specifier
%{ %} Percent curly bracket Block comments
! Exclamation point Operating system command
? Question mark Metaclass for Matlab class
’ ’ Single quotes Character array constructor
" " Double quotes String constructor (since release 2017a) N/A Space character Separator
~ Tilde Logical NOT
Argument placeholder
= Equal sign Assignment
M-File (1)
Standard text file with *.m extension
Allow to reuse sequences of commands by storing them in program files
Script – the simplest type of program
store commands exactly as one would type them at the command line
operate on variables in the workspace no input or output arguments
Function – sub-program with function statement include any valid expressions, control flow statements, comments, blank lines, and nested functions
can pass input values and return output values operate on local variables
M-File (2)
Function syntax
f u n c t i o n [ y1 , . , yN ] = myfun ( x1 , . ,xM)
Declares a function named myfun that accepts inputs x1,. ,xM and returns outputs y1, . ,yN
This declaration statement must be the first executable line of the function
Valid function names begin with an alphabetic character, and can contain letters, numbers, or underscores
The name of the file should match the name of the first function in the file
Files can include multiple local functions or nested functions
Load and store workspace variables Save workspace variables to file
s a v e ( f i l e n a m e )
s a v e ( f i l e n a m e , v a r i a b l e s ) ...
Load variables from file into workspace
l o a d ( f i l e n a m e )
l o a d ( f i l e n a m e , v a r i a b l e s ) ...
If filename is a MAT-file, then load(filename) loads variables in the MAT-File into the Matlab workspace If filename is an ASCII file, then load(filename) creates a double-precision array containing data from the file
Simple I/O
Request user input
x = i n p u t ( prompt ) s t r = i n p u t ( prompt ,' s ')
Displays the text in prompt and waits for the user to input a value. The user can enter expressions, like pi/4 or rand(3), and can use variables in the workspace. With ’s’ returns the entered text, without evaluating the input as an expression.
Display value of variable
d i s p (X)
Displays the value of variable X without printing the variable name
GUI
Graphical User Interfaces
Typically contains controls such as menus, toolbars, buttons, and sliders.
Tools
App Designer – environment for building Matlab apps (layout, behavior)
GUIDE – tools to design user interfaces for custom apps (layout) Matlab contains built-in functionality to help you create the GUI for your app programmatically (layout, behavior)
All Matlab variables are matrices
A vector is a matrix with one row or one column A scalar is a matrix with one row and one column A character string is a row vector of characters (ASCII) The rules of linear algebra apply
Element-by-element creation of vectors and matrices (1)
Vector and matrix elements are enclosed in square brackets Row vector – elements separated with spaces or commas
v1 = [ 1 2 3 ] % row v e c t o r 1 x3 v2 = [ 1 , 2 , 3 ] % row v e c t o r 1 x3
Column vector – elements separated with newline or semicolon
v3 = [ 1 2
3 ] % c o l u m n v e c t o r 3 x1 v4 = [ 1 ; 2 ; 3 ] % c o l u m n v e c t o r 3 x1
Element-by-element creation of vectors and matrices (2) Matrix – rows separated with newline or semicolon, row elements with spaces or commas
m1 = [ 1 2 3 ; 4 5 6 ; 7 8 9 ] % m a t r i x 3 x3 m2 = [ 1 , 2 , 3 ; 4 , 5 , 6 ; 7 , 8 , 9 ] % m a t r i x 3 x3 m3 = [ 1 2 3
4 5 6
7 8 9 ] % m a t r i x 3 x3 m4 = [ 1 , 2 , 3
4 , 5 , 6
7 , 8 , 9 ] % m a t r i x 3 x3
Matrix indexing (1)
Indexing into a matrix is a means of selecting a subset of elements from the matrix
Several indexing styles
Indexing is also closely related to vectorization
Elements of the vectors and matrices are addressed with Fortran-like subscript notation eg. v(1), m(1,2)
Notation is clear from context, but it can be confused with function call
Index start form 1 (unlike C/C++)
Matrix indexing (2)
Indexing vectors (extraction, substitution) scalar subscript
v ( 3 ) % T h i r d e l e m e n t
vector subscript
v ( [ 1 5 ] ) % F i r s t , and f i f t h e l e m e n t s
colon notation
v ( [ 1 : 3 ] ) % F i r s t t h r e e e l e m e n t s
operator end
v ( end ) % L a s t e l e m e n t
v ( 5 : end ) % F i f t h t h r o u g h t h e l a s t
v ( 1 : end −1) % F i r s t t h r o u g h t h e n e x t −t o− l a s t
Matrix indexing (3)
Indexing matrix (extraction, substitution) with two subscripts (similar to vector)
A ( 2 , 4 ) % E l e m e n t i n row 2 , c o l u m n 4 A ( 2 : 4 , 1 : 2 ) % Sub−m a t r i x
A ( 3 , : ) % T h i r d row
linear indexing – one subscript
Matrix indexing (4)
Indexing matrix (extraction, substitution)
Logical indexing – closely related to the find function eg.
A(A > 5)is equivalent to A(find(A > 5))
A(A > 1 2 ) % E l e m e n t s o f A g r e a t e r t h a n 12 B( i s n a n (B) ) = 0 % R e p l a c e a l l NaN e l e m e n t s w i t h z e r o
Colon notation
The colon is one of the most useful operators in Matlab Create vectors, subscript arrays, and specify ’for’ iteration Syntax
x = j:k creates a unit-spaced vector x x = j:i:k creates a regularly-spaced vector x A(:,n) indexing, the nth column of matrix A A(m,:) indexing, the mth row of matrix A A(:,:,p) the pth page of three-dimensional array A A(:) reshapes A into a single column vector A(:,:) reshapes A into a two-dimensional matrix A(j:k) index A with vector j:k, equivalent to
[A(j), A(j+1), ..., A(k)]
A(:,j:k) all subscripts in the first dimension, index second dimension, equivalent to [A(:,j), A(:,j+1), ..., A(:,k)]
Transposition (1)
Transpose vector or matrix
B = A .'
B = t r a n s p o s e (A)
Complex conjugate transpose
C = A'
C = c t r a n s p o s e (A)
Transposition (2)
transpose()vs ctranspose()
>> A = [0 −1 i 2+1 i ;4+2 i 0−2 i ] A =
0 . 0 0 0 0 − 1 . 0 0 0 0 i 2 . 0 0 0 0 + 1 . 0 0 0 0 i 4 . 0 0 0 0 + 2 . 0 0 0 0 i 0 . 0 0 0 0 − 2 . 0 0 0 0 i
>> B = A .' B =
0 . 0 0 0 0 − 1 . 0 0 0 0 i 4 . 0 0 0 0 + 2 . 0 0 0 0 i 2 . 0 0 0 0 + 1 . 0 0 0 0 i 0 . 0 0 0 0 − 2 . 0 0 0 0 i
>> C = A' C =
0 . 0 0 0 0 + 1 . 0 0 0 0 i 4 . 0 0 0 0 − 2 . 0 0 0 0 i 2 . 0 0 0 0 − 1 . 0 0 0 0 i 0 . 0 0 0 0 + 2 . 0 0 0 0 i
Create and combine arrays
zeros Create array of all zeros ones Create array of all ones
rand Uniformly distributed random numbers true Logical 1 (true)
false Logical 0 (false) eye Identity matrix
diag Create diagonal matrix or get diagonal elements of matrix blkdiag Construct block diagonal matrix from input arguments cat Concatenate arrays along specified dimension
horzcat Concatenate arrays horizontally vertcat Concatenate arrays vertically repelem Repeat copies of array elements repmat Repeat copies of array
Create grids
linspace Generate linearly spaced vector logspace Generate logarithmically spaced vector freqspace Frequency spacing for frequency response meshgrid 2-D and 3-D grids
ndgrid Rectangular grid in N-D space
Determine Size and Shape
length Length of largest array dimension size Array size
ndims Number of array dimensions numel Number of array elements isscalar Determine whether input is scalar isvector Determine whether input is vector ismatrix Determine whether input is matrix isrow Determine whether input is row vector iscolumn Determine whether input is column vector isempty Determine whether array is empty
Linear algebra (selected)
inv Matrix inverse
pinv Moore-Penrose pseudoinverse eig Eigenvalues and eigenvectors det Matrix determinant
null Null space rank Rank of matrix
orth Orthonormal basis for range of matrix cond Condition number with respect to inversion trace Sum of diagonal elements
svd Singular value decomposition lu LU matrix factorization
qr Orthogonal-triangular decomposition chol Cholesky factorization
Complex numbers (1)
Matlab automatically performs complex arithmetic Complex numbers are represented in rectangular form The imaginary unit √
−1 is denoted either by i or j Both or either i and j can be reassigned
It is a good idea to reserve either i or j for the unit imaginary value√
−1
>> i a n s =
0 . 0 0 0 0 + 1 . 0 0 0 0 i
>> i = 5 ;
>> i i =
5
Complex numbers (2)
abs Absolute value and complex magnitude angle Phase angle
complex Create complex array conj Complex conjugate
cplxpair Sort complex numbers into complex conjugate pairs
i Imaginary unit
imag Imaginary part of complex number isreal Determine whether array is real
j Imaginary unit
real Real part of complex number sign Sign function (signum function)
unwrap Correct phase angles to produce smoother phase plots
Characters and strings
Character arrays and string arrays provide storage for text data A character array is a sequence of characters, just as a numeric array is a sequence of numbers
c = ' H e l l o World '
A string array is a container for pieces of text, it provides a set of functions for working with text as data (starting in R2017a, strings can be created using double quotes)
s t r = ” G r e e t i n g s f r i e n d ”
Extensive support for string manipulation: create, concatenate, find and replace, join, split, edit, compare, regular expression (read doc)
Conditional statements, loops, branching
if, elseif, else Execute statements if condition is true for Loop to repeat specified number of times
parfor Parallel for loop
switch, case, otherwise Execute one of several groups of statements try, catch Execute statements and catch resulting errors while Loop to repeat when condition is true
break Terminate execution of loop
continue Pass control to next iteration of loop
end Terminate block of code
pause Stop MATLAB execution temporarily
return Return control to invoking function
if, elseif, else
i f e x p r e s s i o n s t a t e m e n t s e l s e i f e x p r e s s i o n
s t a t e m e n t s e l s e
s t a t e m e n t s end
if...end evaluates an expression, and executes a group of statements when the expression is true
The elseif and else blocks are optional.
The statements execute only if previous expressions in the if...end block are false An if block can include multiple elseif blocks
An expression is true when its result is nonempty and contains only nonzero elements
for
f o r i n d e x = v a l u e s s t a t e m e n t s end
for...end executes a group of statements in a loop for a specified number of times valueshas one of the following forms
initV:endV – increment the index variable from initV to endV by 1, and repeat execution of statements until index is greater than endV
initV:step:endV– increment index by the value step on each iteration, or decrements index when step is negative valArray– create a column vector, index, from subsequent columns of array valArrayon each iteration
parfor
p a r f o r l o o p v a r = i n i t v a l : e n d v a l ; s t a t e m e n t s ; end p a r f o r ( l o o p v a r = i n i t v a l : e n d v a l , M) ; s t a t e m e n t s ; end
Executes a series of statements for values of loopvar between initvaland endval, inclusive, which specify a vector of increasing integer values
The loop runs in parallel when you have the Parallel Computing Toolboxor when you create a MEX function or standalone code with MATLAB Coder.
Iterations are not executed in a guaranteed order
Executes statements in a loop using a maximum of M workers or threads, where M is a nonnegative integer.
switch, case, otherwise
s w i t c h s e x p r e s s i o n c a s e c e x p r e s s i o n
s t a t e m e n t s c a s e c e x p r e s s i o n
s t a t e m e n t s ...
o t h e r w i s e s t a t e m e n t s end
Evaluates an s expression and chooses to execute one of several groups of statements
Each choice is a case
The switch block tests each case until one of the c expressions is true When a c expression is true, Matlab executes the corresponding statements and exits the switch block
The otherwise block is optional, Matlab executes the statements only when no case is true.
try, catch
t r y
s t a t e m e n t s c a t c h e x c e p t i o n
s t a t e m e n t s end
Executes the statements in the try block and catches resulting errors in the catch block This approach allows to override the default error behavior for a set of program statements If any statement in a try block generates an error, program control goes immediately to the catch block, which contains custom error handling statements
exceptionis an MException object that allows to identify the error
Both try and catch blocks can contain nested try/catch statements.
while
w h i l e e x p r e s s i o n s t a t e m e n t s end
Evaluates an expression, and repeats the execution of a group of statements in a loop while the expression is true.
An expression is true when its result is nonempty and contains only nonzero elements, otherwise the expression is false
Vectorization (1)
The process of revising loop-based, scalar-oriented code to use Matlab matrix and vector operations
The loop is executed by the Matlab kernel, which is much more efficient at evaluating a loop in interpreted Matlab code Advantages
Appearance– vectorized mathematical code appears more like the mathematical expressions found in textbooks
Less Error Prone– vectorized code is often shorter, thus introduces fewer opportunities to programming errors
Performance – vectorized code often runs much faster than the corresponding code containing loops
Most built-in function support vectorized operations
Vectorization (2)
Loop-based computation of sine on specified interval
i = 0 ;
f o r t = 0 : . 0 1 : 1 0 i = i + 1 ; y ( i ) = s i n ( t ) ; end
Vectorized version
t = 0 : . 0 1 : 1 0 ; y = s i n ( t ) ;
2-D and 3-D Plots
Use plots to visualize data Plot types
Line Plots – linear, log-log, semi-log, error bar plots Pie Charts, Bar Plots, and Histograms – proportion and distribution of data
Discrete Data Plots – stem, stair, scatter plots Polar Plots – plots in polar coordinates
Contour Plots – 2-D and 3-D isoline plots
Vector Fields – comet, compass, feather, quiver and stream plots
Surfaces, Volumes, and Polygons – gridded surface and volume data, ungridded polygon data
Animation – animating plots
Images – read, write, display, and modify images
Line Plots
plot plot3 semilogx semilogy loglog errorbar
fplot fplot3 fimplicit
Pie Charts, Bar Plots, and Histograms
area pie pie3 bar barh bar3
bar3h histogram histogram2 pareto
Discrete Data Plots
stairs stem stem3 scatter scatter3 spy
plotmatrix heatmap
Polar Plots
polarplot polarhistogram polarscatter compass ezpolar
Contour Plots
contour contourf contour3 contourslice fcontour
Vector Fields
quiver quiver3 feather streamslice streamline
Surface and Mesh Plots
surf surfc surfl ribbon pcolor fsurf
fimplicit3 mesh meshc meshz waterfall fmesh
Animation
animatedline comet comet3
Images
image imagesc
Line and Symbol Types (1)
Line Style Description
’-’ Solid line
’--’ Dashed line
’:’ Dotted line
’-.’ Dash-dotted line
’none’ No line
Color Description
’r’ Red
’g’ Green
’b’ Blue
’y’ Yellow
’m’ Magenta
’c’ Cyan
’w’ White
’k’ Black
Line and Symbol Types (2)
Marker Description Marker Description
’o’ Circle ’^’ Upward-pointing triangle
’+’ Plus sign ’v’ Downward-pointing triangle
’*’ Asterisk ’>’ Right-pointing triangle
’.’ Point ’<’ Left-pointing triangle
’x’ Cross ’p’ Five-pointed star (pentagram)
’s’ Square ’h’ Six-pointed star (hexagram)
’d’ Diamond
Multiple plots per figure window (1)
subplot– create a matrix of plots in a single figure window
s u b p l o t (m, n , p )
s u b p l o t (m, n , p ,' r e p l a c e ') s u b p l o t (m, n , p ,' a l i g n ') s u b p l o t (m, n , p , a x )
Divides the current figure into an m-by-n grid and creates axes in the position specified by p. Matlab numbers subplot
positions by row. The first subplot is the first column of the first row, the second subplot is the second column of the first row, and so on
Multiple plots per figure window (2)
s u b p l o t ( 2 , 1 , 1 ) ; x = l i n s p a c e ( 0 , 1 0 ) ; y1 = s i n ( x ) ;
p l o t ( x , y1 )
s u b p l o t ( 2 , 1 , 2 ) ; y2 = s i n ( 5* x ) ; p l o t ( x , y2 )
Plot annotation
axis Set axis limits and aspect ratios grid Display or hide axes grid lines gtext Add text to figure using mouse legend Add legend to axes
text Add text descriptions to data points xlabel Label x-axis
ylabel Label y-axis title Add title