0% found this document useful (0 votes)
93 views

MATLAB Fundamentals - Quick Reference

This document provides a quick reference for visualizing data in MATLAB. It lists common 2D and 3D plot types like scatter, bar, stem, and pie charts. It describes how to customize plots with annotations and string arrays. Matrix multiplication and solving systems of linear equations are also summarized. Functions to modify axis properties like ticks, labels, and limits are shown.

Uploaded by

Chin Alicia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
93 views

MATLAB Fundamentals - Quick Reference

This document provides a quick reference for visualizing data in MATLAB. It lists common 2D and 3D plot types like scatter, bar, stem, and pie charts. It describes how to customize plots with annotations and string arrays. Matrix multiplication and solving systems of linear equations are also summarized. Functions to modify axis properties like ticks, labels, and limits are shown.

Uploaded by

Chin Alicia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM

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

Identifying Available Plot Types

Function Description

scatter Scatter plot, with variable marker size and color

bar Bar graph (vertical and horizontal)


>> M = mean(
(A,dim)
)
stem Discrete sequence (signal) plot
Outputs Inputs
stairs Stairstep graph
M Vector of average values along A Matrix
dimension dim . area Filled area plot
dim Dimension across which the mean
is taken. pie Pie chart
1 : the mean of each column
histogram Histogram
2 : the mean of each row

Matrix Multiplication >> scatter(


(x,y,n,c,filled)
)

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

filled If provided, markers


will be filled in disks.
Otherwise, they are
circles.

See the complete list of all available plots here.

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.

Summary of Visualizing Data in 2D and 3D xticklabels Labels the x-axis ticks.

https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 11 of 37 https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 12 of 37


MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM

xtickangle Rotates the x-axis tick labels. Custom Axis Limits

xlim([
([
([-1 13])
])
ylim([
([
([-1 2])
])
Customizing Plot Properties

Specifying Property Values

(x,y,linespec,Property1,Value1,Property2,Value2,Property3,Value3,...)
plot( )

See the complete list of line specifications here: https://www.mathworks.com/help/matlab/ref/plot.html#btzitot_sep_mw_3a76f056-


2882-44d7-8e73-c695c0c54ca8.

Common line properties to modify:


"LineWidth" (width of the line and marker edges)
"MarkerSize" (size of the marker symbols)
"MarkerEdgeColor" (color of the edge of the marker symbols)
Axis Limits = Data Range
"MarkerFaceColor" (color of the interior of the marker symbols)
"Color" (color of the line, particularly when given as RGB values)
axis tight
MATLAB Line Properties reference

Specifying Colors

red ( "r" ) green ( "g" ) blue ( "b" ) black ( "k" )

magenta ( "m" ) yellow ( "y" ) cyan ( "c" ) white ( "w" )

Or as a vector [[R G B]
] where each value is from 0 to 1.

Axis Control

Plotting Multiple Columns


Get Axes Limits
You can use the plot function on a matrix to plot each column as a separate line in your plot.
v = axis

v =
0 12 0.1 0.9

https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 13 of 37 https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 14 of 37


MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM

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

The surf function plots z(


(j,k)
) over the point x= k and y= j

Conditional Data Selection


Summary of Conditional Data Selection
x = 11:15; Summary: Conditional Data Selection
y = 21:25;
surf(
(x,y,z))
Logical Operations and Variables
To specify x and y coordinates, you can pass them in as vectors.
Here, Relational Operators
The number of elements of x must match the number of v = [[6 7 8 9]
];
== Equal
columns of z w = [[2 4 8 16]];
The number of elements of y must match the number of rows > Greater than NE = v ~= w
of z NE =
< Less than 1 1 0 1
>= Greater than or equal

<= Less than or equal

~= 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

Purpose Function Output

Are any of the elements true? any true/false

Are all the elements true? all true/false

https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 15 of 37 https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 16 of 37


MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM

How many elements are true? nnz double teamWins =

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:

idx = x > 4 Sorting Table Data

EPL = sortrows(
(EPL,"HomeWins")
);
The sortrows function sorts the data
in ascending order, by default.

Step 2: Use the logical vector as an index into another


EPL = sortrows(
(EPL,"HomeWins","descend")
);
array to extract the elements corresponding to the true Use the optional "descend"
values. parameter to sort the list in descending
order.
Example:
EPL = sortrows(
(EPL,[
["HomeWins" "AwayWins"]
],"descend")
);
idx = x > 4 or z = y(
(x > 4)
) You can also sort on multiple variables,
z = y(
(idx)
) in order, by specifying a string array of
variable names.

summary(
(EPL)
)
You can also show summary statistics
for variables in a table.

Extracting Portions of a Table


Tables of Data
Summary of Tables of Data EPL
EPL =
Summary: Tables of Data Team
Team HW
HW HD
HD HL
HL AW
AW AD
AD AL
AL
___________________ __ __ __ __ __ __
"Leicester City" 12 6 1 11 6 2
Storing Data in a Table "Arsenal" 12 4 3 8 7 4
Display the original table.
"Manchester City" 12 2 5 7 7 5
EPL = readtable(
("EPLresults.xlsx","TextType","string")
); "Manchester United" 12 5 2 7 4 8
The readtable function creates a
"Chelsea" 5 9 5 7 5 7
table in MATLAB from a data file.
"Bournemouth" 5 5 9 6 4 9
"Aston Villa" 2 5 12 1 3 15
teamWinsTable = table(
(team,wins)
)

https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 17 of 37 https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 18 of 37


MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM

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.

Extracting Data from a Table


Organizing Tabular Data
EPL Summary of Organizing Tabular Data
EPL =
Team
Team HW
HW HD
HD HL
HL AW
AW AD
AD AL
AL
Summary: Organizing Tabular Data
___________________ __ __ __ __ __ __
Display the original table. "Leicester City" 12 6 1 11 6 2
"Arsenal" 12 4 3 8 7 4 Combining Tables
"Manchester City" 12 2 5 7 7 5
"Manchester United" 12 5 2 7 4 8
If the tables are already aligned so that the rows correspond to the same observation, you can concatenate them with square
brackets.
tw = EPL.HW + EPL.AW
tw = [[teamInfo games]
]
You can use dot notation to 23
extract data for use in 20
calculations or plotting. 19 r
este
19 Leic al
rs en m
A a
enh City
Tott hester ited
c n
Man ester U
EPL.TW = EPL.HW + EPL.AW ch
Man
EPL =
Team
Team HW
HW HD
HD HL
HL AW
AW AD
AD AL
AL TW
TW teamInfo games
You can also use dot ___________________ __ __ __ __ __ __ __
notation to create new "Leicester City" 12 6 1 11 6 2 23
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 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.

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

https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 19 of 37 https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 20 of 37


MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM

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'} }

Working with Dates and Times


Indexing into Cell Arrays
teamInfo

Dates are often automatically detected and brought


https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 21 of 37 https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 22 of 37
MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM

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

Create datetime variables to work with.


seasonEnd = datetime(
(2016,5,17)
)

seasonEnd =
17-May-2016

seasonLength = seasonEnd - seasonStart


seasonLength =
Preprocessing Data
Use subtraction to produce a duration variable.
6792:00:00 Summary of Preprocessing Data
Summary: Preprocessing Data
seasonLength = days(
(seasonLength)
)
Functions such as years and days can help seasonLength =
make better sense of the output. 283 Normalizing Data

seconds(
(5)
) normalize Normalize data using a specified normalization method.

They can also create durations from a numeric ans =


value. 5 seconds
xNorm = normalize(
(x)
)
Normalize the columns of a matrix using
seasonLength = between(
(seasonStart,seasonEnd)
) z-scores.

Use the between function to produce a context-

https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 23 of 37 https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 24 of 37


MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM

Center the mean of the columns in a xNorm = normalize(


(x,"center","mean")
) missing elements. ans =
matrix on zero. 1×7 logical
logical array
0 1 0 0 1 0 1
xNorm = normalize(
(x,"scale","first")
)
Scale the columns of a matrix by the first
element of each column. xNaN = standardizeMissing(
(x,-999)
)
Use the standardizeMissing function xNaN =
xNorm = normalize(
(x,"range",[
[a b])
]) to convert all missing values to NaN . 2 NaN 5 3 NaN 4 NaN
Stretch or compress the data in each
column of a matrix into a specified
interval.
cleanX = rmmissing(
(xNaN)
)

Use the rmmissing function to remove cleanX =


missing values. 2 5 3 4
Working with Missing Data

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.

Data Type Meaning of "Missing"


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
double
double NaN
the Live Editor tab in the toolstrip.
single
single

LIVE EDITOR string array Empty string ( <missing> )

datetime NaT

duration NaN
Task calendarDuration

categorical <undefined>

Interpolating Missing Data

fillmissing Fills missing values of an array or table.

x = [[2 NaN 5 3 -999 4 NaN]


];
Data contains missing values, in the form
of both -999 and NaN .
z = fillmissing(
(y,"method")
)
Interpolation assuming equal spacing of
ismissing(
(x)
) observations.
ans =
The ismissing function identifies only
1×7 logical
logical array z = fillmissing(
(y,"method","SamplePoints",x)
)
the NaN elements by default. Interpolation with given observation
0 1 0 0 0 0 1
locations.

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

https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 25 of 37 https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 26 of 37


MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM

"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(
(...)
)

Plot multiple series together.


Common Data Analysis Techniques
Summary of Common Data Analysis Techniques
Summary: Common Data Analysis Techniques

Moving Window Operations

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

Plot variables against each other.


Task

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 .

Fit polynomial to data.


https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 27 of 37 https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 28 of 37
MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM

Fit polynomial to data.


c = polyfit(
(x,y,n)
); The msgbox , errordlg , and warndlg functions can display
messages to the user.
yfit = polyval(
(c,xfit)
);
Evaluate fitted polynomial.

Fitting with centering and scaling

[[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

Summary of Programming Constructs code_3


Summary: Programming Constructs else
else
If none of the cases are a match, then the code, code_e , in else
else
code_e
is executed.
User Interaction
end
end
Always end the expression with the keyword end
end

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

If expression equals value_1 , then code_1 is executed. code_1


Otherwise, the next case is tested. There can be any number of
cases. case value 2
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")
)

https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 29 of 37 https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 30 of 37


MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM

false . While condition is true , code executes. Once while condition


while
condition becomes false, the loop ceases execution. code
end
end

Increasing Automation with Functions


Summary of Functions
Summary: Increasing Automation with Functions
s = size(
(prices)
)
s = Creating and Calling Functions
19 10
Define a function Call a function
[[m,n]
] = size(
(prices)
)
m =
19
n =
10
Use size to find the dimensions of a matrix.

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

Base Workspace Function Workspace


The condition is a variable or expression that evaluates to true or

https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 31 of 37 https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 32 of 37


MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM

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

MATLAB Path and Calling Precedence

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

A more comprehensive list can be found here.


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.
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.

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

https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 33 of 37 https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 34 of 37


MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM

Mouse over a variable to see its size and a preview.

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

There is a potential for unexpected results or poor code performance.

There are syntax errors that must be addressed.

The Code Analyzer identifies both syntax errors and warnings.

Inspecting Variables

Runtime errors are bugs that aren't syntax errors.


Look at the variables in the Workspace for a preview. Double click them to inspect elements in the Variable Editor.

Stepping Through Code

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 and Advance

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.

Section Break: Add a section break to create a code


section.

This is the current section.

Run and Advance: Run code in the current section,


then move to the next section.

Remove semicolons to inspect the output.

https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 35 of 37 https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 36 of 37


MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM

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.

Add breakpoints by clicking line numbers.

Continue: Run code until the next breakpoint (or the


end of the script).

Step: Run only the next line of code.

Stop: Stop code execution and exit debug mode.

Don't forget to clear your breakpoints and save your work!

A Debugging Workflow

When debugging MATLAB code, a common workflow is as follows.

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

You might also like