MATLAB Fundamentals Quick Reference
MATLAB Fundamentals Quick Reference
1. Introduction
Use the controls in the MATLAB toolstrip to create and run scripts.
Create Run
Code Sections
Code sections allow you to organize your code and run sections of code independently. On the Live Editor tab, in the
Section section, click Section Break to create a new code section, or press Ctrl+Alt+Enter.
Load data
Convert units
Plot data
Label graph
You can run and add code sections in the Section section of the Live Editor tab in the toolstrip.
LIVE EDITOR
Section Break
Run
Run to End
Section
SECTION
To insert a line of text, click the Text button in the Text section of the Live Editor tab in the MATLAB Toolstrip.
Format the text using the formatting options provided in the Text section.
Comments
To create a comment, add % comment where you want to add more information.
load gCosts
Germany = gal2lit*Germany;
Australia = gal2lit*Australia;
Mexico = gal2lit*Mexico;
Save As…
Export to PDF…
Export to Word…
HTML…
LaTeX…
Export Folder…
a =
10 15 20 25
using a semi-colon.
b =
Transpose a Vector
c =
2 3 5 7
Create a Matrix
1 3 5
2 4 6
a =
3 5 7
When Interval is 1
b =
3 4 5 6 7
c =
Concatenating Arrays
Horizontal Concatenation
Vertical Concatenation
Separate elements
using a semicolon (;)
Combined Concatenation
Most of these functions support the calling syntaxes shown below.
Calling Output
syntax
fun(m,n)
m-by-n
fun(n)
n-by-n
Reshaping Arrays
x = rand(260,1);
y = reshape(x,5,52);
Specify the dimensions for the new array.
y = reshape(x,5,[]);
For convenience, you can also leave one of the dimensions blank
when calling reshape and that dimension will be calculated
automatically.
Indexing
1 2 3 4
v M
v(2)
v(end)
v([1 end-2:end])
1.3
0.9
1.3
When you are extracting elements of a matrix you need to provide two indices, the row and column numbers.
M(2,3)
M(:,end)
0.9
0.7
2.5
0.6
M([1 end],2)
2.8
v(2) = 0
2.3
1.3
0.9
1.3
v(1:3) = 0
0.9
1.3
v(1:3) = [3 5 7]
0.9
1.3
v(9) = 42
1.3
42
v(1:3) = []
0.9
42
Changing elements in matrices works the same way as with vectors, but you must specify both rows and columns.
There are many operators that behave in element-wise manner, i.e., the operation is performed on each element of the
array individually.
Mathematical Functions
sin Sine
cos Cosine
log Logarithm
mod Modulus
Many more
Scalar Expansion
Operators
+ Addition
- Subtraction
* Multiplication
/ Division
^ Exponentiation
Arithmetic Operators
Operators
+ Addition
- Subtraction
.* Element-wise Multiplication
./ Element-wise Division
.^ Element-wise Exponentiation
Note that, for performing the arithmetic operations on two matrices, they should have identical dimensions.
Implicit Expansion
Operators
+ Addition
- Subtraction
.* Element-wise Multiplication
./ Element-wise Division
.^ Element-wise Exponentiation
Array operations can be performed on operands of different compatible sizes. Two arrays have compatible sizes if the size of each
dimension is either the same or one.
Function Description
Ignoring NaNs
avg = mean(v,"omitnan")
include:
8 2 4
Function Behavior 3 2 6
7 5 3
8 10 8
Asum = sum(A)
Asum =
25 19 21
Many statistical functions accept an optional dimensional argument that specifies whether the
operation should be applied to columns independently (the default) or to rows.
>> M = mean(A,dim)
Outputs Inputs
M Vector of average values along A Matrix
dimension dim .
dim Dimension across which the mean
is taken.
Matrix Multiplication
Matrix multiplication requires that the inner dimensions agree. The resultant matrix has the outer dimensions.
Expression Interpretation
Function Description
histogram Histogram
>> scatter(x,y,n,c,filled)
Inputs
x x-data
y y-data
n marker size
c color
Customizing Annotations
Arrays of strings are useful for annotating visualizations. Use square brackets, [] , with spaces and
semicolons, ; to
create a string
array the same way you create a numeric matrix.
"hello" "sweet"
"peaceful" "world"
ylabel("\pi r^2")
plot(x,y,linespec,Property1,Value1,Property2,Value2,Property3,Value3,...)
Specifying Colors
Axis Control
v = axis
v =
0 12 0.1 0.9
xlim([-1 13])
ylim([-1 2])
axis tight
You can use the plot function on a matrix to plot each column as a separate line in your plot.
Visualizing Matrices
You can use visualization functions to plot your three-dimensional data.
z =
0 0 0 0 0
z is a 5-by-5 matrix 0 0 -6 0 0
0 -3 1 3 0
0 0 8 1 0
0 0 0 0 0
surf(z)
x = 11:15;
y = 21:25;
surf(x,y,z)
Exporting a Figure
You can either copy and paste output or export a figure as an image file.
Gasoline Prices
Australia
7
Germany
Mexico
Prices (USD/gal)
6
1
1990 1995 2000 2005
Year
Relational Operators
v = [6 7 8 9];
== Equal
w = [2 4 8 16];
NE =
~= Not equal
Logical Operators
v = [6 7 8 9];
& AND
w = [2 4 8 16];
| OR x = 5;
~ NOT
A =
0 0 1 1
Counting Elements
What are the indices of the elements that are true? find double
Logical Indexing
Example:
idx = x > 4
Example:
idx = x > 4
or z = y(x > 4)
z = y(idx)
8. Review Project I
9. Tables of Data
Summary: Tables of Data
EPL = readtable("EPLresults.xlsx","TextType","string");
The readtable function creates a
table in MATLAB from a data file.
teamWinsTable = table(team,wins)
teamWins =
Team Wins
"Chelsea" 12
"Leicester City" 23
"Manchester United" 19
names
to include as variable names
in the table. 20 11 7
12 14 12
23 12 3
19 9 10
EPL = sortrows(EPL,"HomeWins");
The sortrows function sorts the data
in ascending order, by default.
EPL = sortrows(EPL,"HomeWins","descend");
Use the optional "descend"
parameter to sort the list in
descending order.
summary(EPL)
You can also show summary statistics
for variables in a table.
Extracting Portions of a Table
EPL
EPL =
Team HW HD HL AW AD AL
___________________ __ __ __ __ __ __
"Leicester City" 12 6 1 11 6 2
"Arsenal" 12 4 3 8 7 4
"Manchester United" 12 5 2 7 4 8
"Chelsea" 5 9 5 7 5 7
"Bournemouth" 5 5 9 6 4 9
"Aston Villa" 2 5 12 1 3 15
EPL(2:4,[1 2 5])
ans =
Team HW AW
___________________ __ __
names.
EPL
EPL =
Team HW HD HL AW AD AL
___________________ __ __ __ __ __ __
"Arsenal" 12 4 3 8 7 4
"Manchester City" 12 2 5 7 7 5
"Manchester United" 12 5 2 7 4 8
tw = EPL.HW + EPL.AW
tw =
calculations or plotting.
19
19
EPL =
Team HW HD HL AW AD AL TW
variables in a table.
"Arsenal" 12 4 3 8 7 4 20
"Manchester City" 12 2 5 7 7 5 19
"Manchester United" 12 5 2 7 4 8 19
draws =
5 4
2 7
Exporting Tables
You can use the writetable function to create a file from a table.
writetable(tableName,"myFile.txt","Delimeter","\t")
The file format is based on the file extension, such as .txt , .csv , or .xlsx , but you can also specify a delimeter.
Combining Tables
If the tables are already aligned so that the rows correspond to the same observation, you can concatenate them
with
square brackets.
[teamInfo games]
r
este
Leic al
en
Ars ham ity
ten C
To hester ited
t
Ma nc
er Un
t
nches
Ma
teamInfo games
If the tables are not already aligned so that the rows correspond to the same observation, you can
still combine the data
by merging them with a join.
uswntTop3 posTop3
top3 = join(uswntTop3,posTop3)
top3 =
Table Properties
EPL.Properties
ans =
Description: ''
UserData: []
VariableUnits: {}
VariableContinuity: []
RowNames: {}
EPL.Properties.VariableNames
ans =
individual property of
{'Team'} {'HomeWins'} {'HomeDraws'} {'HomeLosses'}
notation.
{'HomeGF'} {'HomeGA'} {'AwayWins'} {'AwayDraws'}
Columns 9 through 11
varNames = teamInfo.Properties.VariableNames
The variable varNames is a
cell array that contains
character arrays of different 'Team' 'Payroll_M__' 'Manager' 'ManagerHireDate'
lengths in each cell.
varName(2)
Using parentheses to index
produces a cell array, not
the character array inside 'Payroll_M__'
the cell.
varName{2}
In order to extract the
contents inside the cell, you
should index using curly 'Payroll_M__'
braces, { } .
varName{2} = 'Payroll'
teamInfo
ans =
Manager ManagerHireDate
_________________ _______________
Dates are often automatically detected and brought in "Rafael Benítez" 3/11/2016
sortrows(teamInfo,"ManagerHireDate")
ans =
Manager ManagerHireDate
_________________ _______________
t = datetime(1977,12,13)
You can create a datetime array using numeric
t =
20-Jul-1969
seasonStart = datetime(2015,8,8)
seasonStart =
08-Aug-2015
seasonEnd =
17-May-2016
seasonLength =
seasonLength = days(seasonLength)
Functions such as years and days can help seasonLength =
seconds(5)
They can also create durations from a numeric ans =
value. 5 seconds
seasonLength = between(seasonStart,seasonEnd)
Use the between function to produce a context- seasonLength =
calmonths(2)
Create a calendar duration from a numeric input
ans =
calyears .
You can learn more about datetime and duration functions in the documentation.
y = categorical(x);
You can convert x into a categorical
array, y , using the categorical y =
function. C B C A B A C
nnz(x == "C")
You can use == to create a logical
array, and count elements using ans =
nnz . 3
summary(y)
You can view category statistics
A B C
y = mergecats(y,["B" "C"],"D")
You can view combine categories
y =
Normalizing Data
xNorm = normalize(x)
Normalize the columns of a matrix using
z-scores.
xNorm = normalize(x,"center","mean")
Center the mean of the columns in a
matrix on zero.
xNorm = normalize(x,"scale","first")
Scale the columns of a matrix by the first
element of each column.
The Clean Missing Data task can be used to remove or interpolate missing data. You can add one to a script by selecting
it from the Live Editor tab in the toolstrip.
LIVE EDITOR
Task
ismissing(x)
ans =
ismissing(x,[-999,NaN])
Specifying the set of missing values ans =
missing elements. 0 1 0 0 1 0 1
xNaN = standardizeMissing(x,-999)
Use the standardizeMissing function to xNaN =
cleanX = rmmissing(xNaN)
missing values. 2 5 3 4
max
cov
min mean
median
std
var
Data Type Meaning of "Missing"
double
NaN
single
datetime NaT
duration
NaN
calendarDuration
categorical <undefined>
z = fillmissing(y,"method")
Interpolation assuming equal spacing of
observations.
z = fillmissing(y,"method","SamplePoints",x)
Interpolation with given observation
locations.
Method Meaning
"next" The missing value is the same as the next nonmissing value in the data.
"previous" The missing value is the same as the previous nonmissing value in the data.
"nearest" The missing value is the same as the nearest (next or previous) nonmissing value in the data.
"linear" The missing value is the linear interpolation (average) of the previous and next nonmissing values.
"spline" Cubic spline interpolation matches the derivatives of the individual interpolants at the data points. This
results in an interpolant that is smooth across the whole data set. However, this can also introduce
spurious oscillations in the interpolant between data points.
"pchip" The cubic Hermite interpolating polynomial method forces the interpolant to maintain the same
monotonicity as the data. This prevents oscillation between data points.
The Smooth Data task can be used to smooth variation or noise in data. You can add one to a
script by selecting it from
the Live Editor tab in the toolstrip.
LIVE EDITOR
Task
z = smoothdata(y,"movmean",k)
Mean calculated with a centered moving
k-point window.
z = smoothdata(y,"movmean",[kb kf])
Mean calculated with a moving window
with kb points backward and kf points
forward from the current point.
z = smoothdata(y,"movmedian",k)
Median calculated with a centered moving
k-point window.
z = smoothdata(y,"movmedian",k,"SamplePoints",x)
Median calculated with a centered moving
k-point window using sample points
defined in
x .
Linear Correlation
plot(...)
yyaxis right
plot(...)
plotmatrix(data)
corrcoef(data)
ans =
Polynomial Fitting
Simple fitting
c = polyfit(x,y,n);
Fit polynomial to data.
yfit = polyval(c,xfit);
Evaluate fitted polynomial.
[c,~,scl] = polyfit(x,y,n);
Fit polynomial to data.
yfit = polyval(c,xfit,[],scl);
Evaluate fitted polynomial.
User Interaction
You can add a live control to get input from the user.
disp("Message")
You can use disp to show output on the command window.
Message
warning("Missing data")
Missing data
msgbox("Analysis complete")
Decision Branching
if condition_1
code_1
elseif condition_2
code_2
code_3
else
If none of the cases are a match, then the code, code_e , in else
code_e
is executed.
end
Always end the expression with the keyword end
switch expression
Evaluate expression to return a value.
case value 1
code_2
otherwise
end
Always end the expression with the keyword end
Determining Size
s = size(prices)
s =
19 10
[m,n] = size(prices)
m =
19
n =
m = size(prices,1)
m =
19
n = size(prices,2)
n =
10
m = length(Year)
Use length when working with vectors where one of the m =
N = numel(prices)
Use numel to find the total number of elements in an array of any
N =
dimension.
190
For Loops
for index = first:increment:last
The index is defined as a vector. Note the use of the colon code
syntax to define the values that the index will take. end
While Loops
while condition
false .
While condition is true , code executes. Once
end
condition becomes false, the loop ceases execution.
Function Files
Local functions:
Functions:
Workspaces
A function maintains its own workspace to store variables created in the function body.
foo.mlx
1. function y = foo(x)
a = 42;
2. a = sin(x);
b = foo(a);
3. x = x + 1;
4. b = sin(x);
5. y = a*b;
6. end
a 42 a -0.9165
x 43
y 0.7623
In MATLAB, there are rules for interpreting any named item. These rules are referred to as the function
precedence order.
Most of the common reference conflicts can be resolved using the following order:
1. Variables
2. Functions defined in the current script
3. Files in the current folder
4. Files on MATLAB search path
The search path, or path is a subset of all the folders in the file system. MATLAB can access all files in the folders on the
search path.
Code Analyzer
Use the MATLAB Code Analyzer. messages shown in the Editor to identify and fix syntax errors.
The small red icon at the top of the Code Analyzer. indicates there are errors in the script. Click
on it to show red lines
identifying the locations of syntax errors.
Red indicator lines in the Code Analyzer. identify specific syntax errors. You can mouse over one to
see a
description of
that issue. The first indicator line describes the mistake
you saw in the error message: the closing quotation mark is
missing.
Clicking an indicator
line
puts your cursor where the error was found so you can fix it. Notice that the
broken portion of
the
code is red and underlined.
After you fix the error, the code in line 1 is no longer red and underlined. The corresponding
indicator
line
goes away.
There is still one syntax error left, though. You should fix all syntax errors flagged by the
Code Analyzer before running
your script or function.
Icon Meaning
Inspecting Variables
Run time errors can produce an execution-stopping error or just be something you
didn't mean
to do. An effective way to
troubleshoot them is to inspect variables.
Remove semicolons to inspect the output.
Click on a variable to view each place where the variable is used, created, or
modified. Click the gray indicator lines in the
Code Analyzer to go directly to the line
where a
variable is used.
Look at the variables in the Workspace for a preview. Double click them to inspect
elements in the Variable Editor.
When variables change throughout a script, you can step through your code to inspect
intermediate values. You can run
section by section or set breakpoints.
You can run scripts section by section. In the Section section of the Live Editor tab in the
Toolstrip, you can break up
your code into
sections to run one at a time.
Setting Breakpoints
You can also set breakpoints in scripts and functions to stop code execution before specific lines. This works
particularly
well with
functions, where you otherwise don't have access to the workspace. Breakpoints give you access to the same
tools
you have in scripts for inspecting variables.
A Debugging Workflow
18. Conclusion