MATLAB
Notes for Professionals
MATLAB®
Notes for Professionals
100+ pages
of professional hints and tricks
GoalKicker.com
Free Programming Books
Disclaimer
This is an unocial free book created for educational purposes and is
not aliated with ocial MATLAB® group(s) or company(s).
All trademarks and registered trademarks are
the property of their respective owners
Contents
About
...................................................................................................................................................................................
1
Chapter 1: Getting started with MATLAB Language
...................................................................................
2
...................................................................................................................
3
..........................................................................................
8
Section 1.1: Indexing matrices and arrays
Section 1.2: Anonymous functions and function handles
Section 1.3: Matrices and Arrays
Section 1.4: Cell arrays
Section 1.5: Hello World
Section 1.6: Scripts and Functions
Section 1.7: Helping yourself
Section 1.8: Data Types
Section 1.9: Reading Input & Writing Output
Chapter 2: Initializing Matrices or arrays
................................................................................................................................
................................................................................................................................................
...............................................................................................................................................
..............................................................................................................................
.......................................................................................................................................
...............................................................................................................................................
............................................................................................................
.......................................................................................................
Section 2.1: Creating a matrix of 0s
Section 2.2: Creating a matrix of 1s
Section 2.3: Creating an identity matrix
...........................................................................................................................
...........................................................................................................................
....................................................................................................................
21
Chapter 3: Conditions
Section 3.1: IF condition
Section 3.2: IF-ELSE condition
Section 3.3: IF-ELSEIF condition
Section 3.4: Nested conditions
...............................................................................................................................................
...............................................................................................................................................
....................................................................................................................................
.................................................................................................................................
23
...................................................................................................................................
24
Chapter 4: Functions
................................................................................................................................................
27
Section 4.1: nargin, nargout
Chapter 5: Set operations
........................................................................................................................................
27
......................................................................................................................................
29
Section 5.1: Elementary set operations
Chapter 6: Documenting functions
.....................................................................................................................
29
....................................................................................................................
30
Section 6.1: Obtaining a function signature
Section 6.2: Simple Function Documentation
Section 6.3: Local Function Documentation
Section 6.4: Documenting a Function with an Example Script
..............................................................................................................
...........................................................................................................
.............................................................................................................
...............................................................................
31
Chapter 7: Using functions with logical output
...........................................................................................
34
Section 7.1: All and Any with empty arrays
...............................................................................................................
34
Chapter 8: For loops
.................................................................................................................................................
35
Section 8.1: Iterate over columns of matrix
Section 8.2: Notice: Weird same counter nested loops
Section 8.3: Iterate over elements of vector
Section 8.4: Nested Loops
Section 8.5: Loop 1 to n
Section 8.6: Loop over indexes
..........................................................................................................................................
...............................................................................................................................................
..................................................................................................................................
..............................................................................................................
35
...........................................................................................
35
............................................................................................................
Chapter 9: Object-Oriented Programming
....................................................................................................
40
Section 9.1: Value vs Handle classes
Section 9.2: Constructors
Section 9.3: Defining a class
Section 9.4: Inheriting from classes and abstract classes
.........................................................................................................................
............................................................................................................................................
.......................................................................................................................................
......................................................................................
43
Chapter 10: Vectorization
.......................................................................................................................................
47
Section 10.1: Use of bsxfun
Section 10.2: Implicit array expansion (broadcasting) [R2016b]
..........................................................................................................................................
47
............................................................................
48
11
13
14
14
16
16
19
21
21
21
22
22
22
30
30
30
36
37
38
39
40
40
42
Section 10.3: Element-wise operations
Section 10.4: Logical Masking
Section 10.5: Sum, mean, prod & co
Section 10.6: Get the value of a function of two or more arguments
.....................................................................................................................................
Advertisement
..........................................................................................................................
......................................................................................................................
....................................................................
52
Chapter 11: Matrix decompositions
Section 11.1: Schur decomposition
Section 11.2: Cholesky decomposition
Section 11.3: QR decomposition
Section 11.4: LU decomposition
Section 11.5: Singular value decomposition
....................................................................................................................
..............................................................................................................................
.......................................................................................................................
..................................................................................................................................
..................................................................................................................................
..............................................................................................................
55
Chapter 12: Graphics: 2D Line Plots
...................................................................................................................
56
Section 12.1: Split line with NaNs
Section 12.2: Multiple lines in a single plot
Section 12.3: Custom colour and line style orders
.................................................................................................................................
................................................................................................................
...................................................................................................
57
Chapter 13: Graphics: 2D and 3D Transformations
...................................................................................
61
Section 13.1: 2D Transformations
...............................................................................................................................
61
Chapter 14: Controlling Subplot coloring in MATLAB
...............................................................................
64
Section 14.1: How it's done
..........................................................................................................................................
64
Chapter 15: Image processing
Section 15.1: Basic image I/O
Section 15.2: Retrieve Images from the Internet
Section 15.3: Filtering Using a 2D FFT
Section 15.4: Image Filtering
Section 15.5: Measuring Properties of Connected Regions
..............................................................................................................................
......................................................................................................................................
......................................................................................................
.......................................................................................................................
.......................................................................................................................................
.....................................................................................
67
Chapter 16: Drawing
Section 16.1: Circles
Section 16.2: Arrows
Section 16.3: Ellipse
Section 16.4: Pseudo 4D plot
Section 16.5: Fast drawing
Section 16.6: Polygon(s)
..................................................................................................................................................
......................................................................................................................................................
.....................................................................................................................................................
71
......................................................................................................................................................
74
......................................................................................................................................
75
..........................................................................................................................................
..............................................................................................................................................
Chapter 17: Financial Applications
.....................................................................................................................
82
Section 17.1: Random Walk
Section 17.2: Univariate Geometric Brownian Motion
.........................................................................................................................................
82
..............................................................................................
82
Chapter 18: Fourier Transforms and Inverse Fourier Transforms
....................................................
84
Section 18.1: Implement a simple Fourier Transform in MATLAB
Section 18.2: Images and multidimensional FTs
Section 18.3: Inverse Fourier Transforms
......................................................................................................
..................................................................................................................
...........................................................................
84
Chapter 19: Ordinary Dierential Equations (ODE) Solvers
.................................................................
92
Section 19.1: Example for odeset
................................................................................................................................
92
Chapter 20: Interpolation with MATLAB
..........................................................................................................
94
Section 20.1: Piecewise interpolation 2 dimensional
Section 20.2: Piecewise interpolation 1 dimensional
Section 20.3: Polynomial interpolation
................................................................................................
94
................................................................................................
96
...................................................................................................................
101
Chapter 21: Integration
..........................................................................................................................................
105
Section 21.1: Integral, integral2, integral3
................................................................................................................
105
Chapter 22: Reading large files
........................................................................................................................
107
Section 22.1: textscan
................................................................................................................................................
107
49
50
51
53
53
53
54
54
56
56
65
65
65
65
66
70
70
79
80
85
90
Section 22.2: Date and time strings to numeric array fast
..................................................................................
107
Chapter 23: Usage of accumarray() Function
.........................................................................................
109
Section 23.1: Apply Filter to Image Patches and Set Each Pixel as the Mean of the Result of Each Patch
.............................................................................................................................................................................
109
Section 23.2: Finding the maximum value among elements grouped by another vector
................................
110
Chapter 24: Introduction to MEX API
.............................................................................................................
111
Section 24.1: Check number of inputs/outputs in a C++ MEX-file
Section 24.2: Input a string, modify it in C, and output it
Section 24.3: Passing a struct by field names
Advertisement
Section 24.4: Pass a 3D matrix from MATLAB to C
........................................................................
111
......................................................................................
........................................................................................................
...............................................................................................
Chapter 25: Debugging
..........................................................................................................................................
116
Section 25.1: Working with Breakpoints
Section 25.2: Debugging Java code invoked by MATLAB
..................................................................................................................
116
...................................................................................
118
Chapter 26: Performance and Benchmarking
...........................................................................................
121
Section 26.1: Identifying performance bottlenecks using the Profiler
Section 26.2: Comparing execution time of multiple functions
Section 26.3: The importance of preallocation
Section 26.4: It's ok to be single!
......................................................................................................
............................................................................................................................
.................................................................
121
............................................................................
Chapter 27: Multithreading
.................................................................................................................................
130
Section 27.1: Using parfor to parallelize a loop
Section 27.2: Executing commands in parallel using a "Single Program, Multiple Data" (SPMD) statement
......................................................................................................
130
.............................................................................................................................................................................
130
Section 27.3: Using the batch command to do various computations in parallel
Section 27.4: When to use parfor
Chapter 28: Using serial ports
............................................................................................................................
...........................................................................................................................
.............................................
131
Section 28.1: Creating a serial port on Mac/Linux/Windows
Section 28.2: Choosing your communication mode
Section 28.3: Automatically processing data received from a serial port
Section 28.4: Reading from the serial port
Section 28.5: Closing a serial port even if lost, deleted or overwritten
Section 28.6: Writing to the serial port
Chapter 29: Undocumented Features
.............................................................................................................
...............................................................
....................................................................................................................
............................................................................................................
...............................................................................
..............................................................................................
..........................................................
136
Section 29.1: Color-coded 2D line plots with color data in third dimension
Section 29.2: Semi-transparent markers in line and scatter plots
Section 29.3: C++ compatible helper functions
Section 29.4: Scatter plot jitter
Section 29.5: Contour Plots - Customise the Text Labels
Section 29.6: Appending / adding entries to an existing legend
......................................................................................................
.................................................................................................................................
......................................................................................
.........................................................................
........................................................
138
.......................................................................
Chapter 30: MATLAB Best Practices
Section 30.1: Indent code properly
Section 30.2: Avoid loops
Section 30.3: Keep lines short
Section 30.4: Use assert
Section 30.5: Block Comment Operator
Section 30.6: Create Unique Name for Temporary File
...............................................................................................................
..........................................................................................................................
.........................................................................................................................................
..................................................................................................................................
...........................................................................................................................................
.................................................................................................................
........................................................................................
148
Chapter 31: MATLAB User Interfaces
..............................................................................................................
150
Section 31.1: Passing Data Around User Interface
Section 31.2: Making a button in your UI that pauses callback execution
Section 31.3: Passing data around using the "handles" structure
..........................................................
152
........................................................................
153
.................................................................................................
150
112
113
113
124
125
127
131
133
133
133
137
137
137
138
138
140
141
141
143
145
145
146
146
147
147
Section 31.4: Performance Issues when Passing Data Around User Interface
...................................................
154
Chapter 32: Useful tricks
.......................................................................................................................................
157
Section 32.1: Extract figure data
Section 32.2: Code Folding Preferences
Section 32.3: Functional Programming using Anonymous Functions
Section 32.4: Save multiple figures to the same .fig file
Section 32.5: Comment blocks
Section 32.6: Useful functions that operate on cells and arrays
..............................................................................................................................
.................................................................................................................
.................................................................
160
........................................................................................
.................................................................................................................................
.........................................................................
Chapter 33: Common mistakes and errors
.................................................................................................
165
....................................................................................................................
Section 33.1: The transpose operators
Section 33.2: Do not name a variable with an existing function name
Section 33.3: Be aware of floating point inaccuracy
Section 33.4: What you see is NOT what you get: char vs cellstring in the command window
Section 33.5: Undefined Function or Method X for Input Arguments of Type Y
Section 33.6: The use of "i" or "j" as imaginary unit, loop indices or common variable
Section 33.7: Not enough input arguments
Section 33.8: Using length for multidimensional arrays
Section 33.9: Watch out for array size changes
............................................................................................................
......................................................................................
Advertisement
....................................................................................................
........................
167
.................................................
....................................
.............................................................................................
...............................................................
............................................................................................................................................................................
......................................................................................................................................................
177
Credits
You may also like
157
158
160
161
162
165
165
166
168
169
172
173
173
175
About
Please feel free to share this PDF with anyone for free,
latest version of this book can be downloaded from:
https://goalkicker.com/MATLABBook
This MATLAB® Notes for Professionals book is compiled from Stack Overflow
Documentation, the content is written by the beautiful people at Stack Overflow.
Text content is released under Creative Commons BY-SA, see credits at the end
of this book whom contributed to the various chapters. Images may be copyright
of their respective owners unless otherwise specified
This is an unofficial free book created for educational purposes and is not
affiliated with official MATLAB® group(s) or company(s) nor Stack Overflow. All
trademarks and registered trademarks are the property of their respective
company owners
The information presented in this book is not guaranteed to be correct nor
accurate, use at your own risk
Please send feedback and corrections to [email protected]
GoalKicker.com – MATLAB® Notes for Professionals
1
Chapter 1: Getting started with MATLAB
Language
Version Release Release Date
1.0
1984-01-01
2
3
3.5
4
4.2c
5.0
5.1
5.1.1
5.2
1986-01-01
1987-01-01
1990-01-01
1992-01-01
1994-01-01
Volume 8 1996-12-01
Volume 9 1997-05-01
R9.1
R10
1997-05-02
1998-03-01
5.2.1
R10.1
1998-03-02
5.3
R11
1999-01-01
5.3.1
R11.1
1999-11-01
6.0
6.1
6.5
6.5.1
6.5.2
7
R12
2000-11-01
R12.1
2001-06-01
R13
2002-06-01
R13SP2
2003-01-01
R13SP2
2003-01-02
R14
2006-06-01
7.0.4
R14SP1
2004-10-01
7.1
7.2
7.3
7.4
7.5
7.6
7.7
7.8
7.9
7.10
7.11
7.12
7.13
7.14
8.0
8.1
8.2
8.3
8.4
8.5
8.6
R14SP3
2005-08-01
R2006a
2006-03-01
R2006b 2006-09-01
R2007a
2007-03-01
R2007b 2007-09-01
R2008a
2008-03-01
R2008b 2008-09-01
R2009a
2009-03-01
R2009b 2009-09-01
R2010a
2010-03-01
R2010b 2010-09-01
R2011a
2011-03-01
R2011b 2011-09-01
R2012a
2012-03-01
R2012b 2012-09-01
R2013a
2013-03-01
R2013b 2013-09-01
R2014a
2014-03-01
R2014b 2014-09-01
R2015a
2015-03-01
R2015b 2015-09-01
GoalKicker.com – MATLAB® Notes for Professionals
2
9.0
9.1
9.2
Advertisement
R2016a
2016-03-01
R2016b 2016-09-14
R2017a
2017-03-08
See also: MATLAB release history on Wikipedia.
Section 1.1: Indexing matrices and arrays
MATLAB allows for several methods to index (access) elements of matrices and arrays:
Subscript indexing - where you specify the position of the elements you want in each dimension of the
matrix separately.
Linear indexing - where the matrix is treated as a vector, no matter its dimensions. That means, you specify
each position in the matrix with a single number.
Logical indexing - where you use a logical matrix (and matrix of true and false values) with the identical
dimensions of the matrix you are trying to index as a mask to specify which value to return.
These three methods are now explained in more detail using the following 3-by-3 matrix M as an example:
>> M = magic(3)
ans =
8 1 6
3 5 7
4 9 2
Subscript indexing
The most straight-forward method for accessing an element, is to specify its row-column index. For example,
accessing the element on the second row and third column:
>> M(2, 3)
ans =
7
The number of subscripts provided exactly matches the number of dimensions M has (two in this example).
Note that the order of subscripts is the same as the mathematical convention: row index is the first. Moreover,
MATLAB indices starts with 1 and not 0 like most programming languages.
You can index multiple elements at once by passing a vector for each coordinate instead of a single number. For
example to get the entire second row, we can specify that we want the first, second and third columns:
>> M(2, [1,2,3])
ans =
3 5 7
In MATLAB, the vector [1,2,3] is more easily created using the colon operator, i.e. 1:3. You can use this in indexing
as well. To select an entire row (or column), MATLAB provides a shortcut by allowing you just specify :. For example,
the following code will also return the entire second row
GoalKicker.com – MATLAB® Notes for Professionals
3
>> M(2, :)
ans =
3 5 7
MATLAB also provides a shortcut for specifying the last element of a dimension in the form of the end keyword. The
end keyword will work exactly as if it was the number of the last element in that dimension. So if you want all the
columns from column 2 to the last column, you can use write the following:
>> M(2, 2:end)
ans =
5 7
Subscript indexing can be restrictive as it will not allow to extract single values from different columns and rows; it
will extract the combination of all rows and columns.
>> M([2,3], [1,3])
ans =
3 7
4 2
For example subscript indexing cannot extract only the elements M(2,1) or M(3,3). To do this we must consider
linear indexing.
Linear indexing
MATLAB allows you to treat n-dimensional arrays as one-dimensional arrays when you index using only one
dimension. You can directly access the first element:
>> M(1)
ans =
8
Note that arrays are stored in column-major order in MATLAB which means that you access the elements by first
going down the columns. So M(2) is the second element of the first column which is 3 and M(4) will be the first
element of the second column i.e.
>> M(4)
ans =
1
There exist built-in functions in MATLAB to convert subscript indices to linear indices, and vice versa: sub2ind and
ind2sub respectively. You can manually convert the subscripts (r,c) to a linear index by
idx = r + (c-1)*size(M,1)
To understand this, if we are in the first column then the linear index will simply be the row index. The formula
above holds true for this because for c == 1, (c-1) == 0. In the next columns, the linear index is the row number
GoalKicker.com – MATLAB® Notes for Professionals
4
plus all the rows of the previous columns.
Note that the end keyword still applies and now refers to the very last element of the array i.e. M(end) == M(end,
end) == 2.
You can also index multiple elements using linear indexing. Note that if you do that, the returned matrix will have
the same shape as the matrix of index vectors.
M(2:4) returns a row vector because 2:4 represents the row vector [2,3,4]:
>> M(2:4)
ans =
3 4 1
As another example, M([1,2;3,4]) returns a 2-by-2 matrix because [1,2;3,4] is a 2-by-2 matrix as well. See the
below code to convince yourself:
>> M([1,2;3,4])
ans =
8 3
4 1
Note that indexing with : alone will always return a column vector:
>> M(:)
ans =
8
3
4
1
5
9
6
7
2
This example also illustrates the order in which MATLAB returns elements when using linear indexing.
Logical indexing
The third method of indexing is to use a logical matrix, i.e. a matrix containing only true or false values, as a mask
to filter out the elements you don't want. For example, if we want to find all the elements of M that are greater than
5 we can use the logical matrix
>> M > 5
ans =
1 0 1
0 0 1
0 1 0
GoalKicker.com – MATLAB® Notes for Professionals
5
to index M and return only the values that are greater than 5 as follows:
>> M(M > 5)
ans =
8
9
6
7
If you wanted these number to stay in place (i.e. keep the shape of the matrix), then you could assign to the logic
compliment
>> M(~(M > 5)) = NaN
ans =
8 NaN 6
NaN NaN 7
NaN 9 Nan
We can reduce complicated code blocks containing if and for statements by using logical indexing.
Take the non-vectorized (already shortened to a single loop by using linear indexing):
for elem = 1:numel(M)
if M(elem) > 5
M(elem) = M(elem) - 2;
end
end
This can be shortened to the following code using logical indexing:
idx = M > 5;
M(idx) = M(idx) - 2;
Or even shorter:
M(M > 5) = M(M > 5) - 2;
More on indexing
Higher dimension matrices
All the methods mentioned above generalize into n-dimensions. If we use the three-dimensional matrix M3 =
rand(3,3,3) as an example, then you can access all the rows and columns of the second slice of the third
dimension by writing
>> M(:,:,2)
You can access the first element of the second slice using linear indexing. Linear indexing will only move on to the
second slice after all the rows and all the columns of the first slice. So the linear index for that element is
>> M(size(M,1)*size(M,2)+1)
GoalKicker.com – MATLAB® Notes for Professionals
6
In fact, in MATLAB, every matrix is n-dimensional: it just happens to be that the size of most of the other n-
dimensions are one. So, if a = 2 then a(1) == 2 (as one would expect), but also a(1, 1) == 2, as does a(1, 1, 1)
== 2, a(1, 1, 1, ..., 1) == 2 and so on. These "extra" dimensions (of size 1), are referred to as singleton
dimensions. The command squeeze will remove them, and one can use permute to swap the order of dimensions
around (and introduce singleton dimensions if required).
An n-dimensional matrix can also be indexed using an m subscri...