MATLAB Fundamentals - Quick Reference
MATLAB Fundamentals - Quick Reference
Many statistical functions accept an optional dimensional argument that specifies whether the
operation should be applied to columns independently (the default) or to rows. Summary: Visualizing Data in 2D and 3D
Function Description
Inputs
Matrix multiplication requires that the inner dimensions agree. The resultant matrix has the outer dimensions.
x x-data
y y-data
n marker size
c color
Customizing Annotations
Solving Systems of Linear Equations 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.
Expression Interpretation
x = [["hello" "sweet";"peaceful" "world"]
]
x = B/A Solves x*A = B (for x ) x =
2×2 string
string array
x = A\B Solves A*x = B (for x ) "hello" "sweet"
"peaceful" "world"
ylabel(
("\pi r^2")
)
You can use markup in your labels.
Visualizing Data in 2D and 3D xticks Sets tick locations along the x-axis.
xlim([
([
([-1 13])
])
ylim([
([
([-1 2])
])
Customizing Plot Properties
(x,y,linespec,Property1,Value1,Property2,Value2,Property3,Value3,...)
plot( )
Specifying Colors
Or as a vector [[R G B]
] where each value is from 0 to 1.
Axis Control
v =
0 12 0.1 0.9
Visualizing Matrices
Gasoline Prices
Australia
You can use visualization functions to plot your three-dimensional data. 7
Germany
Mexico
Prices (USD/gal)
z 6
z =
5
0 0 0 0 0
z is a 5-by-5 matrix 0 0 -6 0 0 4
0 -3 1 3 0
0 0 8 1 0 3
0 0 0 0 0
2
surf(
(z)
) 1
1990 1995 2000 2005
Year
~= Not equal
Exporting a Figure
Logical Operators
You can either copy and paste output or export a figure as an image file. v = [[6 7 8 9]
];
& AND
w = [[2 4 8 16]];
| OR x = 5;
A = ((v > x)
) & ((w > x)
)
~ NOT A =
0 0 1 1
Counting Elements
What are the indices of the elements that are true? find double The table function can create a table Team
Team Wins
Wins
from workspace variables. ___________________ ____
"Arsenal" 20
Logical Indexing "Chelsea" 12
"Leicester City" 23
"Manchester United" 19
Purpose: Select the elements of an array based on certain
criteria.
stats = array2table(
(wdl, ...
"VariableNames",[["Wins" "Draws" "Losses"])
])
stats =
The array2table function can
convert a numeric array to a table. The Wins
Wins Draws
Draws Losses
Losses
VariableNames property can be ____ _____ ______
specified as a string array of names to
include as variable names in the table. 20 11 7
12 14 12
Step 1: Create a logical vector by evaluating the given
23 12 3
condition.
19 9 10
Example:
EPL = sortrows(
(EPL,"HomeWins")
);
The sortrows function sorts the data
in ascending order, by default.
summary(
(EPL)
)
You can also show summary statistics
for variables in a table.
EPL(
(2:4,[
[1 2 5])
]) draws13 = EPL{[
{[
{[1 3]
],[
["HD" "AD"]}
]}
ans = Specify row indices to draws =
Team
Team HW
HW AW
AW extract specific rows. 6 6
Inside parenthesis, specify the
___________________ __ __ 2 7
row numbers of the observations
"Arsenal" 12 8
and column numbers of the table
"Manchester City" 12 7
variables you would like to select.
"Manchester United" 12 7
Exporting Tables
You can use the writetable function to create a file from a table.
EPL(
(2:4,[
["Team" "HW" "AW"])
])
You may also use the name of the ans = (tableName,"myFile.txt","Delimiter","\t")
writetable( )
variable for indexing. Team
Team HW
HW AW
AW
___________________ __ __
The file format is based on the file extension, such as .txt , .csv , or .xlsx , but you can also specify a delimiter.
If you want to reference more "Arsenal" 12 8
than one variable, use a string "Manchester City" 12 7 writetable Write a table to a file.
array containing the variable "Manchester United" 12 7
names.
draws = EPL{
{:,[
["HD" "AD"]}
]}
draws =
If you want to extract 6 6
multiple variables, you can 4 7
do this using curly braces. 2 7
5 4
uswntTop3 posTop3
top3 = join(
(uswntTop3,posTop3)
)
top3 =
Player
Player Goals
Goals Position
Position varNames = teamInfo.Properties.VariableNames
The join function can ___________________
___________________ ______
______ ___________________
___________________ The variable varNames is a
combine tables with a cell array that contains
common variable. "Alex Morgan" 6 "forward" character arrays of different 'Team' 'Payroll_M__' 'Manager' 'ManagerHireDate'
"Megan Rapinoe" 6 "forward" lengths in each cell.
"Rose Lavelle" 3 "midfielder"
varName(
(2)
)
Using parentheses to index
produces a cell array, not the
'Payroll_M__'
character array inside the cell.
Table Properties
EPL.Properties varName{
{2}
}
ans = In order to extract the contents
Table
Table Properties
Properties with properties
properties: inside the cell, you should index
'Payroll_M__'
using curly braces, {{ }} .
Description: ''
UserData: []
[]
DimensionNames: {{'Row' 'Variable'}
} varName{
{2}
} = 'Payroll'
Display the table properties.
VariableNames: {{1×11 cell
cell}}
VariableDescriptions: {{1×11 cell
cell}} Using curly braces allows you to
VariableUnits: {}
{} rename the variable. 'Team' 'Payroll' 'Manager' 'ManagerHireDate'
VariableContinuity: []
[]
RowNames: {}
{}
CustomProperties: No custom properties
properties are set.
EPL.Properties.VariableNames
ans =
1×11 cell
cell array
You can access an individual Columns 1 through 4
property of Properties using {{'Team'}
} {{'HomeWins'} } {{'HomeDraws'} } {{'HomeLosses'}
} Specialized Data Types
Columns 5 through 8
dot notation. Summary of Specialized Data Types
{{'HomeGF'}
} {{'HomeGA'}} {{'AwayWins'}} {{'AwayDraws'}
}
Columns 9 through 11 Summary: Specialized Data Types
{{'AwayLosses'}} {{'AwayGF'}
} {{'AwayGA'} }
Dates are often automatically detected and brought Use the between function to produce a context-
in as datetime arrays. ans = dependent calendarDuration variable. seasonLength =
Manager
Manager ManagerHireDate
ManagerHireDate 9mo 9d
_________________
_________________ _______________
_______________
"Rafael Benítez" 3/11/2016
"Claudio Ranieri" 7/13/2015 calmonths(
(2)
)
"Ronald Koeman" 6/16/2014 Create a calendar duration from a numeric input ans =
"David Unsworth" 5/12/2016 with functions such as calmonths and calyears . 2mo
"Slaven Bilić" 6/9/2015
sortrows(
(teamInfo,"ManagerHireDate")
)
ans = You can learn more about datetime and duration functions in the documentation.
Manager
Manager ManagerHireDate
ManagerHireDate Create Date and Time Arrays
_________________
_________________ _______________
_______________
Many functions operate on datetime arrays directly, "Ronald Koeman" 6/16/2014
such as sortrows . "Slaven Bilić" 6/9/2015
Representing Discrete Categories
"Claudio Ranieri" 7/13/2015
"Rafael Benítez" 3/11/2016
"David Unsworth" 5/12/2016 x = [["C" "B" "C" "A" "B" "A" "C"]
];
x is a string array. x =
"C" "B" "C" "A" "B" "A" "C"
t = datetime(
(1977,12,13)
)
You can create a datetime array using numeric y = categorical(
(x)
);
t = You can convert x into a categorical
inputs. The first input is year, then month, then day.
13-Dec-1977 array, y , using the categorical y =
function. C B C A B A C
ts = datetime([
([
([1903;1969]
],[
[12;7]
],[
[17;20])
])
To create a vector, you can specify an array as input ts = nnz(
(x == "C")
)
to the datetime function. 17-Dec-1903 You can use == to create a logical
20-Jul-1969 ans =
array, and count elements using nnz .
3
summary(
(y)
)
You can view category statistics using
Operating on Dates and Times AA BB CC
the summary function.
2 2 3
seasonStart = datetime(
(2015,8,8)
) y = mergecats(
(y,[
["B" "C"]
],"D")
)
seasonStart = You can view combine categories
y =
08-Aug-2015 using the mergecats function.
D D D A D A D
seasonEnd =
17-May-2016
seconds(
(5)
) normalize Normalize data using a specified normalization method.
Any calculation involving NaN results in NaN . There are three ways to work around this, each with advantages and
disadvantages:
Ignores NaN
NaN s by default Includes NaN
NaN s by default
Ignore missing data when performing Maintains the integrity of the data but can be difficult to implement for (default flag is "omitnan"
"omitnan" ) (default flag is "includenan"
"includenan" )
calculations. involved calculations.
max cov
Remove missing data. Simple but, to keep observations aligned, must remove entire rows of the min mean
matrix where any data is missing, resulting in a loss of valid data. median
std
Replace missing data. Keeps the data aligned and makes further computation straightforward, but
var
modifies the data to include values that were not actually measured or
observed.
datetime NaT
duration NaN
Task calendarDuration
categorical <undefined>
ismissing(
(x,[
[-999,NaN])
])
Method Meaning
Specifying the set of missing values
"next" The missing value is the same as the next nonmissing value in the data.
ensures that ismissing identifies all the
"previous" The missing value is the same as the previous nonmissing value in the data.
Linear Correlation
"nearest" The missing value is the same as the nearest (next or previous) nonmissing value in the data.
You can investigate relationships between variables visually and computationally:
"linear" The missing value is the linear interpolation (average) of the previous and next nonmissing values. Plot multiple series together. Use yyaxis to add another vertical axis to allow for different scales.
Plot variables against each other. Use plotmatrix to create an array of scatter plots.
"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 Calculate linear correlation coefficients. Use corrcoef to calculate pairwise correlations.
oscillations in the interpolant between data points.
"pchip" The cubic Hermite interpolating polynomial method forces the interpolant to maintain the same monotonicity as
yyaxis left
the data. This prevents oscillation between data points.
plot(
(...)
)
yyaxis right
plot(
(...)
)
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 plotmatrix(
(data)
)
Editor tab in the toolstrip.
LIVE EDITOR
corrcoef(
(data)
)
ans =
The Smooth Data task uses the smoothdata function. 1.0000 0.8243 0.1300 0.9519
Calculate linear correlation coefficients.
0.8243 1.0000 0.1590 0.9268
z = smoothdata(
(y,"movmean",k)
)
Mean calculated with a centered moving 0.1300 0.1590 1.0000 0.2938
k-point window. 0.9519 0.9268 0.2938 1.0000
z = smoothdata(
(y,"movmean",[
[kb kf])
])
Mean calculated with a moving window
with kb points backward and kf points Polynomial Fitting
forward from the current point.
z = smoothdata(
(y,"movmedian",k)
) polyfit Fits a polynomial to data.
Median calculated with a centered moving
k-point window. polyval Evaluates a polynomial at specified locations.
z = smoothdata(
(y,"movmedian",k,"SamplePoints",x)
)
Median calculated with a centered moving
k-point window using sample points Simple fitting
defined in x .
[[c,~,scl]
] = polyfit(
(x,y,n)
);
Fit polynomial to data.
Decision Branching
yfit = polyval(
(c,xfit,[]
[]
[],scl)
);
Evaluate fitted polynomial. if condition_1
if
The condition_1 is evaluated as true or false .
code_1
If condition_1 is true , then the code_1 code block is
executed.
elseif condition_2
elseif
code_2
Otherwise, the next case is tested. There can be any number of
Programming Constructs cases.
elseif condition_3
elseif
switch expression
switch
Evaluate expression to return a value.
You can add a live control to get input from the user.
case value 1
case
disp(
("Message")
) code_2
You can use disp to show output on the command window.
Message
otherwise
otherwise
If none of the cases are a match, then the code, code_3 , in
warning(
("Missing data")
)
otherwise
otherwise is executed. The otherwise
otherwise block is optional. code_3
Warning: Missing data
end
end
You can use warning and error as well. Always end the expression with the keyword end
end
error(
("Missing data")
)
Missing data
Determining Size
msgbox(
("Analysis complete")
)
m = size(
(prices,1)
)
m =
19 Function Files
n = size(
(prices,2)
) Function Type Function Visibility
n = Local functions:
Visible only within the file where they are defined.
10 Functions that are defined within a script.
Functions:
Visible to other script and function files.
m = length(
(Year)
) Functions that are defined in separate files.
Use length when working with vectors where one of the m =
dimensions returned by size is 1 . 19
Workspaces
N = numel(
(prices)
)
Use numel to find the total number of elements in an array of any A function maintains its own workspace to store variables created in the function body.
N =
dimension.
190
a = 42; foo.mlx
1. function
function y = foo(
(x)
)
2. a = sin(
(x)
);
For Loops 3. x = x + 1;
4. b = sin(
(x)
);
b = foo(
(a)
); 5. y = a*b;
for index = first:increment:last
for
The index is defined as a vector. Note the use of the colon syntax 6. end
end
code
to define the values that the index will take. end
end
While Loops
a 42 a -0.9165 Use the MATLAB Code Analyzer. messages shown in the Editor to identify and fix syntax errors.
b 0.7623 b -0.8318
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
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.
Troubleshooting Code
Summary of Troubleshooting Code
Summary: Troubleshooting Code
Code Analyzer
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.
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.
Icon Meaning
Inspecting Variables
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.
Run time errors can produce an execution-stopping error or just be something you didn't mean to do. An effective way to 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
troubleshoot them is to inspect variables. 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
Note that after you've identified and fixed any bugs, you should stop your debugging session, save your changes, and clear all
breakpoints before running your code again.
https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 37 of 37