MATLAB Fundamentals Quick Reference
MATLAB Fundamentals Quick Reference
MATLAB Fundamentals
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.
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 1/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
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
% Converts from US$/gal to US$/L
gal2lit = 0.2642; % conversion factor
Germany = gal2lit*Germany;
Australia = gal2lit*Australia;
Mexico = gal2lit*Mexico;
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 2/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
Save As…
Export to PDF…
Export to Word…
HTML…
LaTeX…
Export Folder…
Transpose a Vector
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 3/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
c =
2 3 5 7
Create a Matrix
When Interval is 1
Concatenating Arrays
Horizontal Concatenation
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 4/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
Vertical Concatenation
Separate elements
using a semicolon (;)
Combined Concatenation
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 5/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
Calling Output
syntax
fun(m,n)
m-by-n
fun(n)
n-by-n
Reshaping Arrays
x = rand(260,1);
Create a vector of random numbers to reshape.
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.
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 6/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
Indexing
1 2 3 4
v M
v(2)
Extract one element from a vector
1.5
v(end)
Extract the last element from a vector
1.3
v([1 end-2:end])
2.3
Extract multiple elements from a vector
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)
Extract one element from a matrix
1.7
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 7/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
0.9
1.4
0.7
2.5
0.6
M([1 end],2)
v(2) = 0
2.3
Change one element from a vector 0
1.3
0.9
1.3
v(1:3) = 0
0
Change multiple element of a vector to the same value 0
0
0.9
1.3
v(1:3) = [3 5 7]
3
Change multiple element of a vector to different values 5
7
0.9
1.3
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 8/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
3
5
7
0.9
1.3
0
0
0
42
v(1:3) = []
0.9
1.3
Remove elements from a vector
0
0
0
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.
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 9/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
Mathematical Functions
sin Sine
cos Cosine
log Logarithm
mod Modulus
Many more
Operators
+ Addition
- Subtraction
* Multiplication
/ Division
^ Exponentiation
(Matrix
exponentiation)
Element-wise Operations
Operators
+ Addition
- Subtraction
.* Element-wise Multiplicatio
./ Element-wise Division
.^ Element-wise Exponentiat
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 10/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
Implicit Expansion
Operators
+ Addition
- Subtraction
.* Element-wise Multiplicatio
./ Element-wise Division
.^ Element-wise Exponentiat
Array operations can be performed on operands of different compatible sizes. Two arrays have compatible sizes if the size o
dimension is either the same or one.
Function Description
Ignoring NaNs
avg = mean(v,"omitnan")
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 11/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
Function Behavior
var Variance
A = [8 2 4 ; 3 2 6 ; 7 5 3 ; 7 10 8]
A =
8 2 4
3 2 6
7 5 3
7 10 8
Amax = max(A)
Amax =
8 10 8
Astd = std(A)
Astd =
Asum = sum(A)
Asum =
25 19 21
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 12/43
1/8/25, 7:29 AM 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.
>> M = mean(A,dim)
Outputs Inputs
M Vector of average values along A Matrix
dimension dim .
dim Dimension across which the mean
is taken.
1 : the mean of each column
2 : the mean of each row
Matrix Multiplication
Matrix multiplication requires that the inner dimensions agree. The resultant matrix has the outer
dimensions.
Expression Interpretation
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 13/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
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.
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 14/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
ylabel("\pi r^2")
You can use markup in your labels.
plot(x,y,linespec,Property1,Value1,Property2,Value2,Property3,Value3,...)
Specifying Colors
Axis Control
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 15/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
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.
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 16/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
Visualizing Matrices
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 17/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
z
z =
0 0 0 0
z is a 5-by-5 matrix 0 0 -6 0
0 -3 1 3
0 0 8 1
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.
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 18/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
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];
> Greater than NE = v ~= w
NE =
< Less than
1 1 0 1
>= Greater than or equal
~= Not equal
Logical Operators
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
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 19/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
What are the indices of the elements that are true? find double
Logical Indexing
Example:
idx = x > 4
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 20/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
Example:
Tables of Data
Summary of 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
The table function can ___________________ ____
create a table from
workspace variables. "Arsenal" 20
"Chelsea" 12
"Leicester City" 23
"Manchester United" 19
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 21/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
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.
EPL
EPL =
Team HW HD HL AW AD
___________________ __ __ __ __ __
"Leicester City" 12 6 1 11 6
"Arsenal" 12 4 3 8 7
Display the original table.
"Manchester City" 12 2 5 7 7
"Manchester United" 12 5 2 7 4
"Chelsea" 5 9 5 7 5
"Bournemouth" 5 5 9 6 4
"Aston Villa" 2 5 12 1 3
EPL(2:4,[1 2 5])
Inside parenthesis, specify
the row numbers of the
observations and column
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 22/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
EPL
EPL =
Team HW HD HL AW AD
___________________ __ __ __ __ __
Display the original table. "Leicester City" 12 6 1 11 6
"Arsenal" 12 4 3 8 7
"Manchester City" 12 2 5 7 7
"Manchester United" 12 5 2 7 4
tw = EPL.HW + EPL.AW
tw =
You can use dot notation to 23
extract data for use in 20
calculations or plotting. 19
19
EPL =
Team HW HD HL AW AD
You can also use dot ___________________ __ __ __ __ __
notation to create new "Leicester City" 12 6 1 11 6
variables in a table. "Arsenal" 12 4 3 8 7
"Manchester City" 12 2 5 7 7
"Manchester United" 12 5 2 7 4
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 23/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
draws =
Specify row indices to
6 6
extract specific rows.
2 7
Exporting Tables
You can use the writetable function to create a file from a table.
writetable(tableName,"myFile.txt","Delimiter","\t")
The file format is based on the file extension, such as .txt , .csv , or .xlsx , but you can also specify a
delimiter.
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
en C
Tott hester ited
an c r Un
M ste
a nche
M
teamInfo games
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 24/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
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 =
Player Goals Position
The join function can ___________________ ______ ___________________
combine tables with a
common variable. "Alex Morgan" 6 "forward"
"Megan Rapinoe" 6 "forward"
"Rose Lavelle" 3 "midfielder"
Table Properties
EPL.Properties
ans =
Table Properties with properties:
Description: ''
UserData: []
DimensionNames: {'Row' 'Variable'}
Display the table properties.
VariableNames: {1×11 cell}
VariableDescriptions: {1×11 cell}
VariableUnits: {}
VariableContinuity: []
RowNames: {}
CustomProperties: No custom properties are set.
EPL.Properties.VariableNames
ans =
1×11 cell array
You can access an
Columns 1 through 4
individual property of
{'Team'} {'HomeWins'} {'HomeDraws'} {'HomeL
Properties using dot
Columns 5 through 8
notation.
{'HomeGF'} {'HomeGA'} {'AwayWins'} {'AwayDr
Columns 9 through 11
{'AwayLosses'} {'AwayGF'} {'AwayGA'}
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 25/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
varNames = teamInfo.Properties.VariableNames
The variable varNames is a
cell array that contains
character arrays of different 'Team' 'Payroll_M__' 'Manager' 'ManagerHire
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'
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 26/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
teamInfo
ans =
Manager ManagerHireDate
_________________ _______________
Dates are often automatically detected "Rafael Benítez" 3/11/2016
and brought in as datetime arrays. "Claudio Ranieri" 7/13/2015
"Ronald Koeman" 6/16/2014
"David Unsworth" 5/12/2016
"Slaven Bilić" 6/9/2015
sortrows(teamInfo,"ManagerHireDate")
ans =
Manager ManagerHireDate
_________________ _______________
Many functions operate on datetime "Ronald Koeman" 6/16/2014
arrays directly, such as sortrows . "Slaven Bilić" 6/9/2015
"Claudio Ranieri" 7/13/2015
"Rafael Benítez" 3/11/2016
"David Unsworth" 5/12/2016
t = datetime(1977,12,13)
You can create a datetime array using
numeric inputs. The first input is year, t =
then month, then day. 13-Dec-1977
ts = datetime([1903;1969],[12;7],[17;20])
seasonStart = datetime(2015,8,8)
seasonStart =
08-Aug-2015
Create datetime variables to
work with. seasonEnd = datetime(2016,5,17)
seasonEnd =
17-May-2016
seasonLength = days(seasonLength)
Functions such as years and
days can help make better sense
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 27/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
seconds(5)
They can also create durations ans =
from a numeric value. 5 seconds
seasonLength = between(seasonStart,seasonEnd)
Use the between function to
seasonLength =
produce a context-dependent
9mo 9d
calendarDuration variable.
calmonths(2)
Create a calendar duration from a
ans =
numeric input with functions such
2mo
as calmonths and calyears .
You can learn more about datetime and duration functions in the documentation.
Create Date and Time Arrays
x is a string array. x =
"C" "B" "C" "A" "B" "A" "C"
y = categorical(x);
You can convert x into a
categorical array, y , using y =
the categorical function. C B C A B A C
nnz(y == "C")
You can use == to create a
logical array, and count ans =
elements using nnz . 3
summary(y)
You can view category
statistics using the summary A B C
function. 2 2 3
y = mergecats(y,["B" "C"],"D")
You can view combine
categories using the y =
mergecats function. D D D A D A D
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 28/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
Preprocessing Data
Summary of Preprocessing Data
Summary: Preprocessing Data
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.
Any calculation involving NaN results in NaN . There are three ways to work around this, each with
advantages and disadvantages:
Ignore missing data when performing Maintains the integrity of the data but can be difficult to
calculations. implement for involved calculations.
Remove missing data. Simple but, to keep observations aligned, must remove entire
rows of the matrix where any data is missing, resulting in a
loss of valid data.
Replace missing data. Keeps the data aligned and makes further computation
straightforward, but modifies the data to include values that
were not actually measured or observed.
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.
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 29/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
LIVE EDITOR
Task
ismissing(x)
ans =
The ismissing function identifies only
1×7 logical array
the NaN elements by default.
0 1 0 0 0 0 1
ismissing(x,[-999,NaN])
Specifying the set of missing values ans =
ensures that ismissing identifies all the 1×7 logical array
missing elements. 0 1 0 0 1 0 1
xNaN = standardizeMissing(x,-999)
Use the standardizeMissing function to xNaN =
convert all missing values to NaN . 2 NaN 5 3 NaN 4 NaN
cleanX = rmmissing(xNaN)
max cov
min mean
median
std
var
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 30/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
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",[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"
Median calculated with a centered moving
k-point window using sample points
defined in x .
Linear Correlation
yyaxis left
Plot multiple series together.
plot(...)
yyaxis right
plot(...)
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 32/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
plotmatrix(data)
corrcoef(data)
ans =
1.0000 0.8243 0.1300 0.9519
Calculate linear correlation coefficients.
0.8243 1.0000 0.1590 0.9268
0.1300 0.1590 1.0000 0.2938
0.9519 0.9268 0.2938 1.0000
Polynomial Fitting
Simple fitting
c = polyfit(x,y,n);
Fit polynomial to data.
yfit = polyval(c,xfit);
Evaluate fitted polynomial.
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 33/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
[c,~,scl] = polyfit(x,y,n);
Fit polynomial to data.
yfit = polyval(c,xfit,[],scl);
Evaluate fitted polynomial.
Programming Constructs
Summary of Programming Constructs
Summary: Programming Constructs
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")
The msgbox , errordlg , and warndlg functions
can display messages to the user.
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 34/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
Decision Branching
if condition_1
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
code_2
Otherwise, the next case is tested. There can be any number of
cases.
elseif condition_3
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
If none of the cases are a match, then the code, code_3 , in
otherwise is executed. The otherwise block is optional.
code_3
end
Always end the expression with the keyword end
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 35/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
Determining Size
s = size(prices)
s =
19 10
[m,n] = size(prices)
m =
19
n =
10
Use size to find the dimensions of a matrix.
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 =
dimensions returned by size is 1 . 19
N = numel(prices)
Use numel to find the total number of elements in an array of any
N =
dimension.
190
For Loops
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 36/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
While Loops
while condition
The condition is a variable or expression that evaluates to true or
code
false . While condition is true , code executes. Once
end
condition becomes false, the loop ceases execution.
Function Files
Local functions:
Visible only within the file where they are defined.
Functions that are defined within a script.
Functions:
Visible to other script and function files.
Functions that are defined in separate files.
Workspaces
A function maintains its own workspace to store variables created in the function body.
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 37/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
a = 42; foo.mlx
1. function y = foo(x)
2. a = sin(x);
3. x = x + 1;
4. b = sin(x);
b = foo(a); 5. y = a*b;
6. end
a 42 a -0.9165
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
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.
To add folders to the search path:
1. On the Home tab, in the Environment section, click Set Path.
2. Add a single folder or a set of folders using the buttons highlighted below.
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 38/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
Troubleshooting Code
Summary of Troubleshooting Code
Summary: Troubleshooting Code
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.
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 39/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
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
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 40/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
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.
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 41/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
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
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 42/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference
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.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 43/43