Summary: Entering Commands: Creating Variables
Summary: Entering Commands: Creating Variables
Creating Variables
Defining a variable y.
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.
You can use the Import Tool to interactively bring your data into MATLAB.
Saving and Loading Data
save myData
Creates myData.mat containing current workspace variables.
Instead of saving the entire MATLAB workspace, you can selectively save save
individual variables. Saves x and y to someFile.mat. someFile x y
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.
xlabel
Label the x-axis
ylabel
Label the y-axis
legend
Add legend to plot
Example
v = axis
v =
0 12 0.1 0.9
Custom Axis Limits
xlim([-1 13])
ylim([-1 2])
Axis Limits = Data Range
axis tight
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.
To insert a line of text, click the Text button in the Text section of the Live Editor tab in the
MATLAB Toolstrip.
a = [10 15 20 25]
a =
10 15 20 25
Create a Column Vector
Use square brackets and separate the values using a semi-colon.
Example
b = [2;3;5;7]
b =
2
3
5
7
Transpose a Vector
Use the transpose operator
'
.
Example
c = b'
c =
2 3 5 7
Create a Matrix
Use square brackets and enter values row-by-row. Separate values in a row using a comma or a
space, and use a semicolon to start a new row.
Example
A = [1 3 5;2 4 6]
A =
1 3 5
2 4 6
Colon Operator
The colon operator, :, is useful for when you know the desired spacing between elements of the
x = 1:2:7
x =
Creates a vector that starts at 1, ends at 7, and elements are separated
by 2. 1 3 5
7
x = -4:3:8
x =
Creates a vector that starts at -4, ends at 8, and elements are separated
by 3. -4 -1 2
5 8
To create a vector with spacing 1, you can omit the spacing value in the x = 1:4
syntax. MATLAB will use a default spacing of 1. x =
1 2 3
4
x = 1:4:15
x =
The vector always contains the start point, but may or may not contain the
end point. 1 5 9
13
Linspace
In some cases, when creating an evenly-spaced vector, you may know the number of elements you
want the vector to contain, and not the spacing between the elements. In these cases, you can
use linspace.
When
Syntax Vector Created to use
x = a:dx:b When
eleme
nt
spacin
g is
known
x = When
linspace(a, numbe
b,n) r of
eleme
nts is
known
A nice feature of linspace is that it guarantees the resulting vector will contain both the start and
end point specified. Some examples:
x = linspace(1,7,5)
x =
Creates a vector that starts at 1, ends at 7, and
contains 5 elements. 1.0000 2.5000 4.0000
5.5000 7.0000
x = linspace(-pi,pi,4)
x =
Creates a vector that starts at -pi, ends at pi,
and contains 4 elements. -3.1416 -1.0472 1.0472
3.1416
If the number of elements is omitted, linspace defaults to creating a vector with 100 elements.
a = 3:2:7
a =
3 5 7
When Interval is 1
Use the colon operator to separate the starting and the ending value.
Example
b = 3:7
b =
3 4 5 6 7
Given the Start Value, End Value, and Number of Elements
Use the function linspace when the number of elements in the vector are known.
Example
c = linspace(3.2,8.1,5)
c =
3.2 4.42 5.65 6.87 8.1
Create each row separating elements with a comma (,) or space ( ), then separate the rows with
a semicolon (;)
Step 1 - Create an Index
Example
I = 1:3
I =
1 2 3
Step 2 - Indexing
Example
s = v(I)
s =
15 20 25
Step 1 and Step 2
Example
s = v(1:3)
s =
15 20 25
Assign Multiple Elements
Same Value
Example
v(1:3) = 10
v =
10 10 10 30 35
Multiple Values
Example
v(1:3) = [15 10 5]
v =
15 10 5 30 35
If multiple rows are to be extracted, create a vector containing the row numbers and use that as the
row index.
output = M(row,column)
Use the column number or a vector of column numbers to be extracted as the column index.
output = M(row,column)
This is row-comma-column indexing. Separate the row index and column index by a comma.
output = M(row,column)
Extract a single element
output = M(2,3)
M
M
M
M
Mathematical Functions
Other Similar Functions
sin Sine
cos Cosine
log Logarithm
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.
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)
Functio
n Description
Using min and max
Ignoring NaNs
avg = mean(v,'omitnan')
Function Behavior
var Variance
A = [8 2 4 ; 3 2 6 ; 7 5 3 ; 7 10 8]
A =
8 2 4
3 2 6
7 5 3
7 10 8
Amax = max(A)
Amax =
8 10 8
Astd = std(A)
Astd =
2.2174 3.7749
2.2174
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
)
M Vector of average values along dimension dim.
Outputs
A Matrix
Inputs
xticks
Sets tick locations along the x-axis.
xticklabels
Labels the x-axis ticks.
xtickangle
Rotates the x-axis tick labels.
plot(x,y,linespec,Property1,Value1,Property2,Value2,Property3,Value3,...)
z
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
To
specify x and y coordinate
s, 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
~= Not equal
Example
v = [6 7 8 9];
w = [2 4 8 16];
NE = v ~= w
NE =
1 1 0 1
Logical Operators
& AND
| OR
~ NOT
Example
v = [6 7 8 9];
w = [2 4 8 16];
x = 5;
A = (v > x) & (w > x)
A =
0 0 1 1
What are the indices of the elements that are true? find double
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:
Outputs
'EPLresults.xlsx Name of the file you would like to import, entered as text.
'
Inputs
readtable
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
You can index using dot notation with the variable name to extract the contents from a table variable.
variableData = tableName.VariableName
The result from dot indexing has the data type of the underlying data.
Extracting data this way extracts the actual contents of that table variable.
The result will therefore be of the same size and type as the data in the table variable.
EPL
EPL =
Team HW
HD HL AW AD AL
___________________ __
__ __ __ __ __
'Leicester City' 12
6 1 11 6 2
'Arsenal' 12
Display the original table. 4 3 8 7 4
'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
Because the Team variable contains character
EPL.Team
ans =
7x1 cell array
{'Leicester City' }
{'Arsenal' }
data, the new array is a cell array. {'Manchester City' }
{'Manchester United'}
{'Chelsea' }
{'Bournemouth' }
{'Aston Villa' }
EPL.HW
ans =
Because the HW variable contains numeric data 12
(number of home wins), the new array is a 12
numeric array. 12
12
5
5
2
tw = EPL.HW + EPL.AW
tw =
You can use dot notation to extract 23
data for use in calculations or plotting. 20
19
19
draws = EPL{:,{'HD','AD'}}
draws =
If you want to extract multiple variables, 6 6
you can do this using curly braces. 4 7
2 7
5 4
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.
Summary: Combining Tables
EPL
EPL =
Team Points
___________________ ______
'Leicester City' 81
'Arsenal' 71
'Aston Villa' 17
games
games =
Wins
____
23
Display the original tables. 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 share a common variable. 'Leicester City' 81
23
'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
EPL.Properties
ans =
Table Properties with properties:
Description: ''
UserData: []
DimensionNames: {'Row'
Display the table properties. 'Variable'}
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
Columns 1 through 4
{'Team'} {'HomeWins'}
You can access an individual property {'HomeDraws'} {'HomeLosses'}
of Properties using dot notation. Columns 5 through 8
{'HomeGF'} {'HomeGA'}
{'AwayWins'} {'AwayDraws'}
Columns 9 through 11
{'AwayLosses'} {'AwayGF'}
{'AwayGA'}
sortrows(teamInfo,'ManagerHireDate')
ans =
Manager
ManagerHireDate
_________________
Many functions operate on datetime _______________
arrays directly, such as sortrows. 'Ronald Koeman' 6/16/2014
'Slaven Bilić' 6/9/2015
'Claudio Ranieri' 7/13/2015
'Rafael Benítez' 3/11/2016
'David Unsworth' 5/12/2016
ts = datetime([1903;1969],[12;7],
To create a vector, you can specify an [17;20])
array as input to the datetime function. ts =
17-Dec-1903
20-Jul-1969
seasonLength = seasonEnd -
seasonStart
Use subtraction to produce a duration variable. seasonLength =
6792:00:00
seasonLength =
Functions such as years and days can help days(seasonLength)
make better sense of the output. seasonLength =
283
seconds(5)
They can also create durations from a numeric ans =
value. 5 seconds
seasonLength =
Use the between function to produce a context- between(seasonStart,seasonEnd)
dependent calendarDuration variable. seasonLength =
9mo 9d
You can learn more about datetime and duration functions in the documentation.
Create Date and Time Arrays
y = categorical(x);
shifting and scaling data to have zero mean and unit standard deviation (also known as
standardization).
shifting and scaling data into a fixed range, such as [0, 1].
scaling data to have unit length under a given metric.
Typically this requires calculating values by columns or rows, then applying an arithmetic operation
between the matrix and the resulting vector.
normalize
Normalize data using a specified normalization method.
Leave the data as is and ignore Maintains the integrity of the data but can be difficult to
any NaN elements when performing implement for involved calculations.
calculations.
Remove all NaN elements from the Simple but, to keep observations aligned, must remove
data. entire rows of the matrix where any data is missing,
resulting in a loss of valid data.
Replace all NaN elements in the data. Keeps the data aligned and makes further computation
straightforward, but modifies the data to include values
that were not actually measured or observed.
ismissing(x)
The ismissing function identifies only ans =
the NaN elements by default. 1×7 logical array
0 1 0 0 0 0 1
ismissing(x,[-999,NaN])
Specifying the set of missing values ensures ans =
that ismissing identifies all the missing elements. 1×7 logical array
0 1 0 0 1 0 1
xNaN =
standardizeMissing(x,-999)
Use the standardizeMissing function to convert all xNaN =
missing values to NaN. 2 NaN 5 3
NaN 4 NaN
Ignores NaNs by default
(default flag Includes NaNs by default
is 'omitnan') (default flag is 'includenan')
max cov
min mean
median
std
var
Data Type Meaning of "Missing"
double NaN
single
datetime NaT
duration NaN
calendarDuration
categorical <undefined>
>>
yfilled
= fillmissing(
y
,
method
)
yfille Array of data with missing values replaced.
d
Outputs
y Array of data.
Inputs
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.
Scatter Plots
The relationship between two variables can be visualized using a scatter plot.
scatter(residential,commercial)
What if you want to visualize the relationship between three or more variables? You can create scatter
plots for each pair of variables in the data using the function plotmatrix.
plotmatrix
Creates separate scatter plots for each pair of columns in the input matrix.
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.
Plot yyaxis left
multiple plot(...)
series yyaxis right
together. plot(...)
Plot plotmatrix(data)
variables
against
each
other.
Calculat corrcoef(data)
e linear ans =
correlati 1.0000 0.8243 0.1300 0.9519
on 0.8243 1.0000 0.1590 0.9268
coefficie 0.1300 0.1590 1.0000 0.2938
nts. 0.9519 0.9268 0.2938 1.0000
Polynomial Fitting
Determine the coefficients
You can use the function polyfit to compute the coefficients of a least-squares polynomial fit to the
data.
>>
c
= polyfit(
x
,
y
,
n
)
c Vector of polynomial coefficients.
Outputs
Inputs
x = 0:5;
y = [2 1 4 4 3 2];
plot(x,y)
Suppose
that you
have two
vectors x a
nd y.
Fit a c = polyfit(x,y,3)
polynomial c =
of degree 3
to the x- -0.1296 0.6865 -0.1759 1.6746
y data.
Coefficients in the output vector are ordered from the highest to the lowest degree. So, the polynomial
which fits the x-y data can be expressed as:
p(x) = -0.1296 x3 + 0.6865 x2 - 0.1759 x + 1.6746
Given the vector c containing the coefficients of the polynomial, you can evaluate the polynomial at
any value of x using the polyval function.
>>
yFit
= polyval(
c
,
xFit
)
yFi Value of the polynomial at the given points (yFit = p(xFit)).
t
Outputs
Inputs
A common
approach is
to create a
vector of
uniformly
spaced x valu
es.
polyval
Simple fitting
Fit polynomial to data. c = polyfit(x,y,n);
ctry = inputdlg('Enter a
country:');
warning('Missing data')
You can use warning and error as well. Warning: Missing data
error('Missing data')
Missing data
msgbox('Analysis complete')
The msgbox, errordlg,
and warndlg functions can display messages
to the user.
The switch-case Construction
If there is a finite set of discrete possible values for a variable (e.g., a set of menu options or the
number of dimensions of an array), you can use the switch-case construction in place of an if-
elseif-else construction.
code_1
If expression equals value_1, then code_1 is executed. Otherwise, the
case
next case is tested. There can be any number of cases. 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
Here is an example.
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,
code_e
in else is executed.
code_1
If expression equals value_1, then code_1 is executed. 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
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
Local functions:
Visible only within the file where they are
Functions that are defined within a
defined.
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);
3. x = x + 1;
b = foo(a); 4. b = sin(x);
5. y = a*b;
6. end
Base Workspace Function Workspace
42 -0.9165
a a
0.7623 -0.8318
b b
43
x
Function Workspace
0.7623
y
Icon Meaning