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

MATLAB Fundamentals Quick Reference

Uploaded by

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

MATLAB Fundamentals Quick Reference

Uploaded by

Derrick Attoh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference

MATLAB Fundamentals

Using the MATLAB Desktop


Creating Informative Scripts
Summary: Working with Live Scripts

Create and Run a Script

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

Run
Run to End
Section

SECTION

Comments and Text

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;

Exporting Live Script Files

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

You can export your live script and results using


the Save button in the Live Editor tab. Save

Available formats include PDF, Word, HTML, and


LaTeX. Save

Save As…

Export to PDF…

Export to Word…

HTML…

LaTeX…

Export Folder…

Creating and Manipulating Arrays


Summary of Creating and Manipulating Arrays
Summary: Creating and Manipulating Arrays

Manually Entering Arrays

Create a Row Vector

Use square brackets and separate the values a = [10 15 20 25]


using a comma or a space.
a =
10 15 20 25

Create a Column Vector

Use square brackets and separate the values b = [2;3;5;7]


using a semi-colon.
b =
2
3
5
7

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

Use the transpose operator ' . c = b'

c =
2 3 5 7

Create a Matrix

Use square brackets and enter values row-by-row. A = [1 3 5;2 4 6]


Separate values in a row using a comma or a
space, and use a semicolon to start a new row. A =
1 3 5
2 4 6

Creating Evenly-Spaced Vectors

Given the Start Value, End Value, and Interval

Use the colon operator to separate the starting a = 3:2:7


value, interval, and the ending value.
a =
3 5 7

When Interval is 1

Use the colon operator to separate the starting b = 3:7


and the ending value.
b =
3 4 5 6 7

Given the Start Value, End Value, and Number of Elements

Use the function linspace when the number of c = linspace(3.2,8.1,5)


elements in the vector are known.
c =
3.2 4.42 5.65 6.87 8.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

Separate elements using a


comma (,) or space ( )

Vertical Concatenation

Separate elements
using a semicolon (;)

Combined Concatenation

Create each row separating elements with a


comma (,) or space ( ), then separate the rows
with a semicolon (;)

Array Creation Functions

Several functions exist that allow you to create arrays.

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

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

The following column of information is reshaped into a matrix.

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.

Accessing Data in Arrays

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

Summary of Accessing Data in Arrays


Summary: Accessing Data in Arrays

Indexing

1 2 3 4

1 2.3 1 1.5 1.1 2.6 0.9

2 1.5 2 1.5 2.4 1.7 1.4

3 1.3 3 2.5 1.6 1.9 0.7

4 0.9 4 2.4 1.1 1.8 2.5

5 1.3 5 1.9 2.8 0.6 0.6

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

Extract an entire column. Here, it is the last one. M(:,end)

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)

Extract multiple elements from a matrix.


1.1
2.8

Changing Elements in Arrays

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

Assign a non-existent value v(9) = 42

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.

Mathematical and Statistical Operations with Arrays


Summary of Operations with Arrays
Summary: Mathematical and Statistical Operations with Arrays

Performing Operations on Arrays

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

Other Similar Functions

sin Sine

cos Cosine

log Logarithm

round Rounding Operation

sqrt Square Root

mod Modulus

Many more

Matrix Operations (Including Scalar Expansion)

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.

Calculating Statistics of Vectors

Common Statistical Functions

Function Description

min Returns the minimum element

max Returns the maximum element

mean Returns the average of the elements

median Returns the median value of the elements

Using min and max

Ignoring NaNs

When using statistical functions, you can ignore NaN values

avg = mean(v,"omitnan")

Statistical Operations on Matrices

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

Some common mathematical functions which


calculate a value for each column in a matrix
include:

Function Behavior

max Largest elements

min Smallest elements

mean Average or mean


value

median Median value

mode Most frequent values

std Standard deviation

var Variance

sum Sum of elements

prod Product of elements

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 =

2.2174 3.7749 2.2174

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.

Solving Systems of Linear Equations

Expression Interpretation

x = B/A Solves x*A = B (for x )

x = A\B Solves A*x = B (for x )

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

Visualizing Data in 2D and 3D


Summary of Visualizing Data in 2D and 3D
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)

stem Discrete sequence (signal) plot

stairs Stairstep graph

area Filled area plot

pie Pie chart

histogram Histogram

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

Inputs
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

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

x = ["hello" "sweet";"peaceful" "world"]


x =
2×2 string array
"hello" "sweet"
"peaceful" "world"

ylabel("\pi r^2")
You can use markup in your labels.

xticks Sets tick locations along the x-axis.

xticklabels Labels the x-axis ticks.

xtickangle Rotates the x-axis tick labels.

Customizing Plot Properties

Specifying Property Values

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

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)
"MarkerFaceColor" (color of the interior of the marker symbols)
"Color" (color of the line, particularly when given as RGB values)

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

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

Get Axes Limits

v = axis

v =
0 12 0.1 0.9

Custom Axis Limits

xlim([-1 13])
ylim([-1 2])

Axis Limits = Data Range

axis tight

Plotting Multiple Columns

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

You can use visualization functions to plot your three-dimensional data.

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)

The surf function plots z(j,k) over the point x= k and y= j

x = 11:15;
y = 21:25;
surf(x,y,z)

To specify x and y coordinates, you can pass them in as vectors.


Here,
The number of elements of x must match the number of
columns of z
The number of elements of y must match the number of rows
of 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

Conditional Data Selection


Summary of Conditional Data Selection
Summary: Conditional Data Selection

Logical Operations and Variables

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

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

Purpose Function Output

Are any of the elements true? any true/false

Are all the elements true? all true/false

How many elements are true? nnz double

What are the indices of the elements that are true? find double

Logical Indexing

Purpose: Select the elements of an array based on certain


criteria.

Step 1: Create a logical vector by evaluating the given


condition.

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

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


array to extract the elements corresponding to the true
values.

Example:

idx = x > 4 or z = y(x > 4)


z = y(idx)

Tables of Data
Summary of Tables of Data
Summary: Tables of Data

Storing Data in a Table

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

stats = array2table(wdl, ...


The array2table function
"VariableNames",["Wins" "Draws" "Losses"])
can convert a numeric array

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

to a table. The stats =


VariableNames property
can be specified as a string Wins Draws Losses
array of names to include as ____ _____ ______
variable names in the table.
20 11 7
12 14 12
23 12 3
19 9 10

Sorting Table Data

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.

EPL = sortrows(EPL,["HomeWins" "AwayWins"],"descend");


You can also sort on multiple
variables, 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

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

numbers of the table ans =


variables you would like to Team HW AW
select. ___________________ __ __
"Arsenal" 12 8
"Manchester City" 12 7
"Manchester United" 12 7

EPL(2:4,["Team" "HW" "AW"])

You may also use the name ans =


of the variable for indexing. Team HW AW
___________________ __ __
If you want to reference "Arsenal" 12 8
more than one variable, use "Manchester City" 12 7
a string array containing the "Manchester United" 12 7
variable names.

Extracting Data from a Table

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.TW = EPL.HW + EPL.AW

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

draws = EPL{:,["HD" "AD"]}

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

If you want to extract draws =


multiple variables, you can 6 6
do this using curly braces. 4 7
2 7
5 4

draws13 = EPL{[1 3],["HD" "AD"]}

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.

writetable Write a table to a file.

Organizing Tabular Data


Summary of Organizing Tabular Data
Summary: Organizing Tabular Data

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

Indexing into Cell Arrays

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'

Using curly braces allows


you to rename the variable. 'Team' 'Payroll' 'Manager' 'ManagerHire

Specialized Data Types


Summary of Specialized Data Types
Summary: Specialized Data Types

Working with Dates and Times

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])

To create a vector, you can specify an ts =


array as input to the datetime function. 17-Dec-1903
20-Jul-1969

Operating on Dates and Times

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 = seasonEnd - seasonStart


Use subtraction to produce a seasonLength =
duration variable. 6792:00:00

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

of the output. seasonLength =


283

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

Representing Discrete Categories

x = ["C" "B" "C" "A" "B" "A" "C"];

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

normalize Normalize data using a specified normalization method.

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.

xNorm = normalize(x,"range",[a b])


Stretch or compress the data in each
column of a matrix into a specified
interval.

Working with Missing Data

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

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


Data contains missing values, in the form
of both -999 and NaN .

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)

Use the rmmissing function to remove cleanX =


missing values. 2 5 3 4

Ignores NaN s by default Includes NaN s by default


(default flag is "omitnan" ) (default flag is "includenan" )

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

Data Type Meaning of "Missing"

double NaN
single

string array Empty string ( <missing> )

datetime NaT

duration NaN
calendarDuration

categorical <undefined>

Interpolating Missing Data

fillmissing Fills missing values of an array or table.

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.

Common Data Analysis Techniques


Summary of Common Data Analysis Techniques
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 31/43
1/8/25, 7:29 AM MATLAB Fundamentals - Quick Reference

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 Editor tab in the toolstrip.

LIVE EDITOR

Task

The Smooth Data task uses the smoothdata function.


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"
Median calculated with a centered moving
k-point window using sample points
defined in x .

Linear Correlation

You can investigate relationships between variables visually and computationally:


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.
Calculate linear correlation coefficients. Use corrcoef to calculate pairwise correlations.

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)

Plot variables against each other.

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

polyfit Fits a polynomial to data.

polyval Evaluates a polynomial at specified locations.

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

Fitting with centering and scaling

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

Warning: Missing data

You can use warning and error as well.


error("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

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

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

for index = first:increment:last


The index is defined as a vector. Note the use of
code
the colon syntax to define the values that the index
end
will take.

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.

Increasing Automation with Functions


Summary of Functions
Summary: Increasing Automation with Functions

Creating and Calling Functions

Define a function Call a function

Function Files

Function Type Function Visibility

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

Base Workspace Function Workspace

a 42 a -0.9165

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

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

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

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.

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.

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

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.

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

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.

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.

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.

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.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=v1 43/43

You might also like