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

MATLAB Fundamentals Quick Reference

The document provides a summary of MATLAB fundamentals including: - Getting started with MATLAB by entering commands, defining variables, importing and saving data, and obtaining help - Plotting data and adding annotations, titles, labels, legends and modifying axis properties - Creating and running scripts in live editor mode with code sections, comments and formatting text - Manually entering arrays as row vectors, column vectors, matrices and creating evenly spaced vectors by specifying start, end values, and number of points

Uploaded by

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

MATLAB Fundamentals Quick Reference

The document provides a summary of MATLAB fundamentals including: - Getting started with MATLAB by entering commands, defining variables, importing and saving data, and obtaining help - Plotting data and adding annotations, titles, labels, legends and modifying axis properties - Creating and running scripts in live editor mode with code sections, comments and formatting text - Manually entering arrays as row vectors, column vectors, matrices and creating evenly spaced vectors by specifying start, end values, and number of points

Uploaded by

Edrian Pentado
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

5/11/2021 MATLAB Fundamentals - Quick Reference

MATLAB Fundamentals

1. Getting Started
Summary: Entering Commands

Creating Variables

Defining a variable y .

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 1/50
5/11/2021 MATLAB Fundamentals - Quick Reference

Modifying Variables

You can use the Up (↑) and Down (↓) arrows on the keyboard to scroll through previous commands.

Cleaning Up

clear Clears variables from the workspace.

clc Clears the Command Window and moves the cursor to the upper left corner of the window.

Summary: Getting Data into MATLAB

Import Tool

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 2/50
5/11/2021 MATLAB Fundamentals - Quick Reference

You can use the Import Tool to interactively bring your data into MATLAB.

Saving and Loading Data

You can save and load MAT-files programmatically using the save and load commands.

save myData
Creates myData.mat containing current workspace variables.

save someFile x y
Instead of saving the entire MATLAB workspace, you can
selectively save individual variables. Saves x and y to
someFile.mat .

load myData
Loads variables from myData.mat into current workspace.

save Saves workspace variables to a MAT-file.

load Loads variables from a MAT-file into the workspace.

Summary: Obtaining Help

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 3/50
5/11/2021 MATLAB Fundamentals - Quick Reference

The doc function opens the Help Browser.

>> doc

2. Plotting and Common Modifications


Summary: Plotting

plot(Year,Germany)

Here, the plot function


plots Germany against
Year .

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 4/50
5/11/2021 MATLAB Fundamentals - Quick Reference

plot(Australia,Germany,'mo')

You can also use an optional


line specification string to
change properties of the
plot.

To see options for line style,


line color, and marker style,
reference the documentation
for
“Line Specification”.

Issuing the hold on command allows you to plot multiple data sets together on the same axes.

Summary: Annotating Plots

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 5/50
5/11/2021 MATLAB Fundamentals - Quick Reference

Textual information can be added to plots using separate annotation functions. All of these functions
take text input.

title Add title to plot

xlabel Label the x-axis

ylabel Label the y-axis

legend Add legend to plot

Grid lines can be added or removed to plots.

grid Display axes grid lines

Example

title('International Gasoline Prices')


xlabel('Year')
ylabel('Price (USD/L)')
legend('Germany','Australia','Mexico',...
'Location','northwest')
grid on

Summary: Axis Control

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 6/50
5/11/2021 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

3. Working with Live Scripts

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 7/50
5/11/2021 MATLAB Fundamentals - Quick Reference

Scripts and the Base Workspace

Scripts can operate on the variables that are present in the base workspace before the script is run. Similarly, the
variables that are generated after the script is run are stored in the base workspace.

Scripts can use the variables in the base workspace.

Running the script executes the commands.

Variables generated by the script are stored in the base workspace.

Summary: Create and Run a Script

Use the controls in the MATLAB Toolstrip to create and run scripts.

Create Run

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 8/50
5/11/2021 MATLAB Fundamentals - Quick Reference

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

You can use the controls on the Live Editor tab of the toolstrip to create, navigate to, and run
different sections.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 9/50
5/11/2021 MATLAB Fundamentals - Quick Reference

Summary: Comments and Text

Formatted 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 AuDeMx
% 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

You can export your live script and results using


the Save button in the Live Editor tab.

Available formats include PDF, HTML, and LaTeX.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 10/50
5/11/2021 MATLAB Fundamentals - Quick Reference

The saved file will closely resemble the live script when viewed in the Live Editor with output inline.

Plain code files ( .m )

To share your code with users of previous MATLAB versions, you can save a live script as a plain
code file ( .m ). Users will be able to open and run your file, and any formatting will be converted to
comments with markup.

4. Creating and Manipulating Arrays


Summary: Manually Entering Arrays

Create a Row Vector Example

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


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

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 11/50
5/11/2021 MATLAB Fundamentals - Quick Reference

Create a Column Vector Example

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


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

Transpose a Vector Example

Use the transpose operator ' . c = b'

c =
2 3 5 7

Create a Matrix Example

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

Summary: Creating Evenly-Spaced Vectors

Given the Start Value, End Value, and Example


Interval
a = 3:2:7
Use the colon operator to separate the starting
value, interval, and the ending value. a =
3 5 7

When Interval is 1 Example

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 Example


Number of Elements
c = linspace(3.2,8.1,5)
Use the function linspace when the number of
elements in the vector are known. c =
3.2 4.42 5.65 6.87 8.1

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 12/50
5/11/2021 MATLAB Fundamentals - Quick Reference

Summary: Concatenating Arrays

Horizontal Concatenation

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 (;)

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 13/50
5/11/2021 MATLAB Fundamentals - Quick Reference

Summary: Array Creation Functions

Several functions exist that allow you to create arrays.

Most of these functions support the calling syntaxes shown below.

Calling Output
syntax

fun(m,n)
m-by-n

fun(n)
n-by-n

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 14/50
5/11/2021 MATLAB Fundamentals - Quick Reference

Summary: Reshaping Arrays

The following column of information is reshaped into a matrix.

x = rand(260,1);

y = reshape(x,5,52);
Specify the dimensions for the new
array.

y = reshape(x,5,[]);
For convenience, you can also
leave one of the dimensions blank
when calling reshape and that
dimension will be calculated
automatically.

5. Accessing Data in Arrays


Summary: Indexing into Vectors

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 15/50
5/11/2021 MATLAB Fundamentals - Quick Reference

Summary: Accessing Multiple Elements

Extract Multiple Elements

To extract elements from a vector:

Step 1 - Create an Index Example

Create a vector containing the index or locations I = 1:3


of elements to be extracted.
I =
1 2 3

Step 2 - Indexing Example

Use the index inside the parentheses. s = v(I)

s =
15 20 25

Step 1 and Step 2 Example

You can also combine steps 1 and 2. s = v(1:3)

s =
15 20 25

Assign Multiple Elements

Use multiple indexing with assignment to modify multiple elements at once.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 16/50
5/11/2021 MATLAB Fundamentals - Quick Reference

Same Value Example

Assign one value to multiple elements. v(1:3) = 10

v =
10 10 10 30 35

Multiple Values Example

Assign different values to multiple elements. v(1:3) = [15 10 5]

v =
15 10 5 30 35

Summary: Matrix Indexing

Row, Column Indexing

Whether you're indexing into a matrix with scalar values or vector values, the format is always the
same.

Use the row number to index. output = M(row,column)


If multiple rows are to be extracted, create a
vector containing the row numbers and use that
as the row index.

Use the column number or a vector of column output = M(row,column)


numbers to be extracted as the column index.

This is row-comma-column indexing. Separate the output = M(row,column)


row index and column index by a comma.

Extract a single element

output = M(2,3)

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 17/50
5/11/2021 MATLAB Fundamentals - Quick Reference

Extract multiple elements

output = M(2,[3 4])

Extract multiple contiguous elements

output = M(2,2:4)

Extract complete rows or columns

output = M(2,:)

6. Mathematical and Statistical Operations with Arrays


Summary: Performing Array Operations

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=R2020b 18/50
5/11/2021 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

Scalar Expansion

Operators

+ Addition

- Subtraction

* Multiplication

/ Division

^ Exponentiation

Arithmetic Operators

Operators

+ Addition

- Subtraction

.* Element-wise Multiplication

./ Element-wise Division

.^ Element-wise Exponentiation

Note that, for performing the arithmetic operations on two matrices, they should have identical dimensions.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 19/50
5/11/2021 MATLAB Fundamentals - Quick Reference

Implicit Expansion

Operators

+ Addition

- Subtraction

.* Element-wise Multiplication

./ Element-wise Division

.^ Element-wise Exponentiation

Array operations can be performed on operands of different compatible sizes. Two arrays have compatible sizes if the size of each
dimension is either the same or one.

Summary: Matrix Multiplication

Matrix Multiplication

Matrix multiplication requires that the inner dimensions agree. The resultant matrix has the outer
dimensions.

Matrix “Division”

Expression Interpretation

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

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

Summary: Calculating Statistics of Vectors

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 20/50
5/11/2021 MATLAB Fundamentals - Quick Reference

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

Summary: Statistical Operations on Matrices

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 21/50
5/11/2021 MATLAB Fundamentals - Quick Reference

Some common mathematical functions which A = [8 2 4 ; 3 2 6 ; 7 5 3 ; 7 10 8]


calculate a value for each column in a matrix
A =
include:
8 2 4
Function Behavior 3 2 6
7 5 3
max Largest elements
7 10 8
min Smallest elements

mean Average or mean Amax = max(A)


value
Amax =
median Median value
8 10 8
mode Most frequent values

std Standard deviation Astd = std(A)


var Variance Astd =

sum Sum of elements


2.2174 3.7749 2.2174
prod Product of elements

Asum = sum(A)

Asum =

25 19 21

Many statistical functions accept an optional dimensional argument that specifies whether the
operation should be applied to columns independently (the default) or to rows.

>> M = mean(A,dim)

Outputs Inputs
M Vector of average values along A Matrix
dimension dim .
dim Dimension across which the mean
is taken.
1 : the mean of each column
2 : the mean of each row

7. Visualizing Data in 2D and 3D


Summary: Identifying Available Vector Plot Types
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 22/50
5/11/2021 MATLAB Fundamentals - Quick Reference

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

See the complete list of all available plots here.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 23/50
5/11/2021 MATLAB Fundamentals - Quick Reference

Summary: Annotations Using Arrays of Text

Cell arrays of text are useful for annotating visualizations. Use curly braces, {} , to create a
cell array.

xticks Sets tick locations along the x-axis.

xticklabels Labels the x-axis ticks.

xtickangle Rotates the x-axis tick labels.

Summary: Customizing Plot Properties

Specifying Property Values

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

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

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 24/50
5/11/2021 MATLAB Fundamentals - Quick 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.

Summary: Plotting Multiple Columns

You can use the plot function on a matrix to plot each column as a separate line in your plot.

Summary: Visualizing Matrices

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 25/50
5/11/2021 MATLAB Fundamentals - Quick Reference

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

z =

0 0 0 0 0
z is a 5-by-5 matrix 0 0 -6 0 0
0 -3 1 3 0
0 0 8 1 0
0 0 0 0 0

surf(z)

The surf function plots each point 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

8. Conditional Data Selection


Summary: Logical Operations and Variables

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 26/50
5/11/2021 MATLAB Fundamentals - Quick Reference

Relational Operators Example


== Equal
v = [6 7 8 9];
> Greater than w = [2 4 8 16];
NE = v ~= w
< Less than
NE =
>= Greater than or equal 1 1 0 1

<= Less than or equal

~= Not equal

Logical Operators Example


& AND
v = [6 7 8 9];
| OR w = [2 4 8 16];
x = 5;
~ NOT
A = (v > x) & (w > x)
A =
0 0 1 1

Summary: Counting Elements

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

Summary: Logical Indexing

Purpose: Select the elements of an array based on certain


criteria.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 27/50
5/11/2021 MATLAB Fundamentals - Quick Reference

Step 1: Create a logical vector by evaluating the given


condition.

Example:

idx = x > 4

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)

9. Review Project I

10. Tables of Data


Summary: Storing Data in a Table

EPL = readtable('EPLresults.xlsx');
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=R2020b 28/50
5/11/2021 MATLAB Fundamentals - Quick Reference

stats = array2table(wdl, ...


'VariableNames',{'Wins','Draws','Losses'})

stats =
The array2table function can convert a
numeric array to a table. The VariableNames
Wins Draws Losses
property can be specified as a cell array of
____ _____ ______
names to include as variable names in the
table.
20 11 7
12 14 12
23 12 3
19 9 10

Summary: Sorting Rows of 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 cell
array of variable names.

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

Summary: Extracting Portions of a Table

EPL

EPL =
Team HW HD HL AW AD AL
___________________ __ __ __ __ __ __
'Leicester City' 12 6 1 11 6 2
'Arsenal' 12 4 3 8 7 4
Display the original table.
'Manchester City' 12 2 5 7 7 5
'Manchester United' 12 5 2 7 4 8
'Chelsea' 5 9 5 7 5 7
'Bournemouth' 5 5 9 6 4 9
'Aston Villa' 2 5 12 1 3 15

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 29/50
5/11/2021 MATLAB Fundamentals - Quick Reference

EPL(2:4,[1 2 5])

ans =
Team HW AW
Inside parenthesis, specify the
___________________ __ __
row numbers of the
'Arsenal' 12 8
observations and column
'Manchester City' 12 7
numbers of the table variables
'Manchester United' 12 7
you would like to select.

EPL(2:4,{'Team','HW','AW'})

You may also use the name of ans =


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

Summary: Extracting Data from a Table

EPL

EPL =
Team HW HD HL AW AD AL
___________________ __ __ __ __ __ __
Display the original table.
'Leicester City' 12 6 1 11 6 2
'Arsenal' 12 4 3 8 7 4
'Manchester City' 12 2 5 7 7 5
'Manchester United' 12 5 2 7 4 8

tw = EPL.HW + EPL.AW

tw =
You can use dot notation to
23
extract data for use in
20
calculations or plotting.
19
19

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 30/50
5/11/2021 MATLAB Fundamentals - Quick Reference

EPL.TW = EPL.HW + EPL.AW

EPL =
Team HW HD HL AW AD AL TW
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

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

Summary: Exporting Tables

You can use the writetable function to create a file from a table.

writetable(tableName,'myFile.txt')

The file format is based on the file extension, such as .txt , .csv , or .xlsx .

writetable Write a table to a file.

11. Organizing Data


Summary: Combining Tables

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 31/50
5/11/2021 MATLAB Fundamentals - Quick Reference

EPL

EPL =
Team Points
___________________ ______
'Leicester City' 81
'Arsenal' 71
'Aston Villa' 17

games

games =

Wins
____
Display the original tables.

23
20
3

teamInfo

teamInfo =
Team Manager
________________ _________________
'Arsenal' 'Arsène Wenger'
'Aston Villa' 'Eric Black'
'Leicester City' 'Claudio Ranieri'

[EPL games]

ans =
Team Points Wins
You can concatenate tables that
________________ ______ ____
are the same length but do not
'Leicester City' 81 23
share a common variable.
'Arsenal' 71 20
'Aston Villa' 17 3

EPL = join(EPL,teamInfo)
EPL =
Team Points Manager
___________________ ______ ___________________
The join function can combine
tables with a common variable.
'Leicester City' 81 'Claudio Ranieri'
'Arsenal' 71 'Arsène Wenger'
'Aston Villa' 17 'Eric Black'

Summary: Table Properties

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 32/50
5/11/2021 MATLAB Fundamentals - Quick Reference

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'} {'HomeLosses'}
Properties using dot
Columns 5 through 8
notation.
{'HomeGF'} {'HomeGA'} {'AwayWins'} {'AwayDraws'}
Columns 9 through 11
{'AwayLosses'} {'AwayGF'} {'AwayGA'}

Summary: 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' 'ManagerHireDate'
lengths in each cell.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 33/50
5/11/2021 MATLAB Fundamentals - Quick Reference

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

Summary: Working with Dates and Times

teamInfo

ans =
Manager ManagerHireDate
_________________ _______________
Dates are often automatically detected and brought in 'Rafael Benítez' 3/11/2016
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 arrays directly, 'Ronald Koeman' 6/16/2014
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
t =
inputs. The first input is year, then month, then day.
13-Dec-1977

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 34/50
5/11/2021 MATLAB Fundamentals - Quick Reference

ts = datetime([1903;1969],[12;7],[17;20])

To create a vector, you can specify an array as input ts =


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

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

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

seasonLength = days(seasonLength)
Functions such as years and days can help seasonLength =
make better sense of the output. 283

seconds(5)
They can also create durations from a numeric ans =
value. 5 seconds

seasonLength = between(seasonStart,seasonEnd)
Use the between function to produce a context- seasonLength =
dependent calendarDuration variable. 9mo 9d

calmonths(2)
Create a calendar duration from a numeric input
ans =
with functions such as calmonths and
2mo
calyears .

You can learn more about datetime and duration functions in the documentation.
Create Date and Time Arrays

Summary: Representing Discrete Categories


https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 35/50
5/11/2021 MATLAB Fundamentals - Quick Reference

x = {'C','B','C','A','B','A','C'};

x is a cell array.

y = categorical(x);

You can convert x into a categorical array,


y , using the categorical function.

nnz(x == 'C')
You can use == to create a logical array, and
ans =
count elements using nnz .
3

summary(y)
You can view category statistics using the
A B C
summary 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

12. Preprocessing Data

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 36/50
5/11/2021 MATLAB Fundamentals - Quick Reference

Summary: Normalizing Matrix Data

1. Apply statistical function to rows or columns of a matrix. The result is a


vector.

2. Apply array operation to the matrix and the vector. The vector is
"expanded" as necessary to make the operation feasible.

normalize Normalize data using a specified normalization method.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 37/50
5/11/2021 MATLAB Fundamentals - Quick Reference

Summary: Working with Missing Data

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

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

Data Type Meaning of


"Missing"

double NaN
single

cell array of char Empty string ( '' )

datetime NaT

duration NaN
calendarDuration

categorical <undefined>

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 38/50
5/11/2021 MATLAB Fundamentals - Quick Reference

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

13. Common Data Analysis Techniques


Summary: Moving Window Operations

movmin Moving minimum

movmax Moving maximum

movsum Moving sum

movmean Moving mean

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 39/50
5/11/2021 MATLAB Fundamentals - Quick Reference

movmedian Moving median

movstd Moving standard deviation

movvar Moving variance

z = movmean(y,k)
Mean calculated with a centered moving
k-point window.

z = movmean(y,[kb kf])
Mean calculated with a moving window
with kb points backward and kf points
forward from the current point.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 40/50
5/11/2021 MATLAB Fundamentals - Quick Reference

Summary: 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(...)
yyaxis right
plot(...)

Plot multiple series together.

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

Summary: Polynomial Fitting

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 41/50
5/11/2021 MATLAB Fundamentals - Quick Reference

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.

Fitting with centering and scaling

[c,~,scl] = polyfit(x,y,n);
Fit polynomial to data.

yfit = polyval(c,xfit,[],scl);
Evaluate fitted polynomial.

14. Programming Constructs


Summary: User Interaction

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 42/50
5/11/2021 MATLAB Fundamentals - Quick Reference

ctry = inputdlg('Enter a country:');

You can use inputdlg to gather 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.

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

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 43/50
5/11/2021 MATLAB Fundamentals - Quick Reference

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

Summary: Determining Size

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 44/50
5/11/2021 MATLAB Fundamentals - Quick Reference

s = size(prices)
s =
19 10

[m,n] = size(prices)

m =
19
n =
Use size to find the dimensions of a matrix. 10

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

Summary: For Loops

for index = first:increment:last


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

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

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 45/50
5/11/2021 MATLAB Fundamentals - Quick Reference

15. Increasing Automation with Functions


Summary: Creating and Calling Functions

Define a function Call a function

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

Summary: Workspaces

A function maintains its own workspace to store variables created in the function body.

foo.mlx
1. function y = foo(x)
a = 42; 2. a = sin(x);
b = foo(a); 3. x = x + 1;
4. b = sin(x);
5. y = a*b;
6. end

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 46/50
5/11/2021 MATLAB Fundamentals - Quick Reference

Base Workspace Function Workspace

a 42 a -0.9165

b 0.7623 b -0.8318

x 43

y 0.7623

Adding Folders to MATLAB 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.

MATLAB can access the data and code files in the folders on the search path irrespective of the
current folder.

Calling Precedence

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 47/50
5/11/2021 MATLAB Fundamentals - Quick Reference

Using functions reduces the possibility of variable name conflicts. However, you can still have
conflicts if a user-created function has the same name as a built-in MATLAB function or if a variable
has the same name as a function.

Suppose you use a variable named date to store


the date of the first observation from the electricity
data. Base Workspace

elecData = readtable('elec_res.csv'); elecData 315x2 table

date 1x1 datetime


date = elecData.Dates(1)
date =
01-Jan-1990

However, MATLAB has an in-built function also


named date that returns a character vector
containing today's date.
date.m

Now, if you try to use date , will MATLAB refer to


the variable in the Workspace or the function
named date ? or ?
nextDate = date + 1 date date.m

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.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 48/50
5/11/2021 MATLAB Fundamentals - Quick Reference

So, in the example shown above, the variable date is used instead of the function date .

elecData = readtable('elec_res.csv');

date = elecData.Dates(1);
date =
01-Jan-1990

nextDate = date + 1
nextDate =
02-Jan-1990

16. Troubleshooting Code


Summary: Code Analyzer

Use the MATLAB Code Analyzer messages shown in the Editor to identify and fix syntax errors.

Icon Meaning

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

There are syntax errors that must be addressed.

Summary: Debugging Run-Time Errors

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

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 49/50
5/11/2021 MATLAB Fundamentals - Quick Reference

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.

17. Review Project II

18. Conclusion

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlbe&language=en&release=R2020b 50/50

You might also like