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

Summary: Entering Commands: Creating Variables

The document discusses various methods for creating and manipulating arrays in MATLAB, including: 1) Creating evenly-spaced vectors using the colon operator or linspace function when given the start, end, and interval or number of elements. 2) Concatenating arrays horizontally by separating elements with commas or vertically with semicolons. 3) Reshaping arrays into matrices by specifying new dimensions. 4) Indexing into vectors to extract or modify multiple elements using indices.

Uploaded by

Hemant Bhadoria
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views

Summary: Entering Commands: Creating Variables

The document discusses various methods for creating and manipulating arrays in MATLAB, including: 1) Creating evenly-spaced vectors using the colon operator or linspace function when given the start, end, and interval or number of elements. 2) Concatenating arrays horizontally by separating elements with commas or vertically with semicolons. 3) Reshaping arrays into matrices by specifying new dimensions. 4) Indexing into vectors to extract or modify multiple elements using indices.

Uploaded by

Hemant Bhadoria
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 62

Summary: Entering Commands

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.

Summary: Getting Data into MATLAB


Import Tool

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.

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.

Summary: Annotating Plots


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


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

 
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.

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;

Summary: Manually Entering Arrays


Create a Row Vector
Use square brackets and separate the values using a comma or a space.
 
Example

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

vector (and the start and end points).

Syntax Vector Created


x =
a:dx:
b

Here are some examples:

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.

Note that both the colon operator and linspace create row vectors.

Summary: Creating Evenly-Spaced Vectors


Given the Start Value, End Value, and Interval
Use the colon operator to separate the starting value, interval, and the ending value.
 
Example

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

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

Summary: Reshaping Arrays


The following column of information is reshaped into a matrix.
x = rand(260,1);
y =
Specify the dimensions for the new array.
reshape(x,5,52);
For convenience, you can also leave one of the dimensions blank y = reshape(x,5,
when calling reshape and that dimension will be calculated []);
automatically.

Summary: Indexing into Vectors


Introduction: Accessing Multiple Elements
Suppose you want to extract the Australian gasoline prices corresponding to all the years in the
1990s. After creating the index of elements to be extracted, 1:10, you will have to use this index to
extract the actual values.
In this lesson, you will learn to extract and modify multiple elements of a vector.

Summary: Accessing Multiple Elements


Extract Multiple Elements

To extract elements from a vector:

 
Step 1 - Create an Index

Create a vector containing the index or locations of elements to be extracted.

Example

I = 1:3

I =
1 2 3
Step 2 - Indexing

Use the index inside the parentheses.

Example

s = v(I)

s =
15 20 25
Step 1 and Step 2

You can also combine steps 1 and 2.

Example

s = v(1:3)

s =
15 20 25
Assign Multiple Elements

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

Same Value

Assign one value to multiple elements.


 

Example

v(1:3) = 10

v =
10 10 10 30 35
Multiple Values

Assign different values to multiple elements.

Example

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.

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

Extract multiple elements


output = M(2,[3 4])

  M

Extract multiple contiguous elements


output = M(2,2:4)

  M

Extract complete rows or columns


output = M(2,:)

  M

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.

Mathematical Functions
Other Similar Functions

sin Sine

cos Cosine

log Logarithm

roun Rounding Operation


d

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.

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


Common Statistical Functions

Functio
n Description

min Returns the minimum element


Functio
n Description

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


Some common mathematical functions which calculate a value for each column in a matrix include:

Function Behavior

max Largest elements

min Smallest elements


Function Behavior

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

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

di Dimension across which the mean is taken.


m 1: the mean of each column
2: the mean of each row

Inputs

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

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

magenta yellow ('y') cyan ('c') white ('w')


('m')

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
You can use visualization functions to plot your three-dimensional data.

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

The surf function plots surf(z)


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

Summary: Logical Operations and Variables


Relational Operators
== Equal
> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

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

Summary: Counting Elements


Purpose Function Output

Are any of the elements true? any true/false


Purpose Function Output

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.

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 = or z = y(x > 4)


x > 4
z =
y(idx
)

Introduction: Storing Data in a Table


If you have data saved in a spreadsheet or text file, how can you read it into a table in MATLAB?
Team                Home Wins  Home Draws  Away Wins  Away Draws
Arsenal             12         4             8         7
Chelsea              5         9             7         5
Leicester City      12         6            11         6
Manchester United   12         5             7         4

You could use the Import Tool, choosing the Table option.

Alternatively, you can import the data programmatically using the readtable function.


>>
EPL
= readtable(
'EPLresults.xlsx'
)
EP Name of the variable you would like to store your data to in MATLAB, returned as a table array.
L

Outputs

'EPLresults.xlsx Name of the file you would like to import, entered as text.
'

Inputs

readtable

Import a spreadsheet or delimited text file into MATLAB


Summary: Storing Data in a Table
The readtable function creates a EPL = readtable('EPLresults.xlsx');
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, ...


'VariableNames',
The array2table function can {'Wins','Draws','Losses'})
convert a numeric array to a table. stats =
The VariableNames property can be
specified as a cell array of names to Wins Draws Losses
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
The sortrows function sorts EPL = sortrows(EPL,'HomeWins');
the data in ascending order,
by default.

Use the EPL = sortrows(EPL,'HomeWins','descend');


optional 'descend' paramete
r to sort the list in descending
order.

You can also sort on multiple EPL = sortrows(EPL,


variables, in order, by {'HomeWins','AwayWins'},'descend');
specifying a cell array of
variable names.

You can also summary(EPL)


show summary statistics for
variables in a table.

Introduction: Extracting Data from a Table


To perform analysis on the data contained in a table, you'll need to extract the data from the table
before passing it to another function, such as plot.

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

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 extract 23
data for use in calculations or plotting. 20
19
19

You can also use dot notation to create


new variables in a table. EPL.TW = EPL.HW + EPL.AW
EPL =
Team HW HD
HL AW AD AL TW
___________________ __ __
__ __ __ __ __
'Leicester City' 12 6
1 11 6 2 23
'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 multiple variables, 6 6
you can do this using curly braces. 4 7
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.
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'}

Summary: Indexing into Cell Arrays


The varNames = teamInfo.Properties.VariableNames
variable varNames  'Team 'Payroll_M__ 'Manager 'ManagerHireDate
is a cell array that ' ' ' '
contains character
arrays of different
lengths in each
cell.

Using parentheses varName(2)


to index produces 'Payroll_M__'
a cell array, not the
character array
inside the cell.

In order to extract varName{2}


the contents inside 'Payroll_M__'
the cell, you should
index using curly
braces, { }.

Using curly braces varName{2} = 'Payroll'


allows you to 'Team' 'Payroll' 'Manager' 'ManagerHireDate'
rename the
variable.

Summary: Working with Dates and Times


teamInfo
Dates are often automatically detected
ans =
Manager
ManagerHireDate
_________________
_______________
and brought in as datetime arrays. 'Rafael Benítez' 3/11/2016
'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, 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

You can create a datetime array using t = datetime(1977,12,13)


numeric inputs. The first input is year, then t =
month, then day. 13-Dec-1977

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

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

Create a calendar duration from a numeric input calmonths(2)


with functions such ans =
as calmonths and calyears. 2mo

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

Summary: Representing Discrete Categories


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.
You can use == to create a logical nnz(x == 'C')
array, and count elements ans =
using nnz. 3

You can view catgory statistics summary(y)


using the summary function. A B C
2 2 3
y = mergecats(y,{'B','C'},'D')
You can view combine catgories y =
using the mergecats function. D D D A D A
D

Normalizing Matrix Data


As part of your preprocessing before performing your analysis, you may need to normalize your data.
Common normalizations include:

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

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.

Introduction: Working with Missing Data


The electricity data shown below is incomplete: there are months where some of the usage values are
left blank. When imported, these locations are automatically filled with the value NaN.

Residenti Commerci Industria Residenti Commerci Industria


al al l Total al al l Total

2980415   2660526 815796 2980415 NaN 2660526 815796


6 6

3503588 2337908 2675077 878023 3503588 2337908 2675077 878023


1 1

3314413 2396962 2845247 883118


6
 ⇨  3314413 2396962 2845247 883118
6

2807629 2236648 2737563 803322 2807629 2236648 2737563 803322


6 6

2487211 2198899 2738653 767816 2487211 2198899 2738653 767816


6 6

2404723 2277607 2794768   2404723 2277607 2794768 NaN


Any calculation involving NaN results in NaN. There are three ways to work around this, each with
advantages and disadvantages:

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.

Summary: Working with Missing Data


Data contains missing values, in the form of both - x = [2 NaN 5 3 -999 4 NaN];
999 and NaN.

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

cell array of char Empty string ('')

datetime NaT

duration NaN
calendarDuration

categorical <undefined>

ntroduction: Interpolating Missing Data


You can use the fillmissing function to replace missing data with interpolated values.
fillmissing

Replaces missing data values.

>>
yfilled
= fillmissing(
y
,
method
)
yfille Array of data with missing values replaced.
d

Outputs

y Array of data.

method String specifying an interpolation method.

Inputs

Different interpolation methods can produce slightly different results

Summary: Interpolating Missing Data


fillmissing

Fills missing values of an array or table.


Interpolation assuming equal z = fillmissing(y,'method')
spacing of observations.

Interpolation with given observation z =


locations. fillmissing(y,'method','SamplePoints',x)

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.

Summary: Moving Window Operations


movmin Moving minimum

movmax Moving maximum

movsum Moving sum

movmean Moving mean

movmedian Moving median

movstd Moving standard deviation

movvar Moving variance

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

Mean calculated with a moving window with kb points z = movmean(y,


backward and kf points forward from the current point. [kb kf])

Scatter Plots
The relationship between two variables can be visualized using a scatter plot.

scatter(residential,commercial)

Given two vectors


named residential and co
mmercial containing the
electricity usage data, you
can visualize the relationship
between them.

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

x Location of data points (independent variable


values).

y Data to fit polynomial to (y = p(x)).

n Degree of fitted polynomial.

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

Evaluate the polynomial

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

c Vector of polynomial coefficients.

xFit Location of points (independent variable values) at


which to evaluate the polynomial.

Inputs

You can xFit = -1:0.01:6;


evaluate the
polynomial at
any arbitrary
values of x.

A common
approach is
to create a
vector of
uniformly
spaced x valu
es.

Evaluate and xFit = -1:0.01:6;


plot the fitted yFit = polyval(c,xFit);
polynomial at hold on
values plot(xFit,yFit)
contained in hold off
the
vector xFit.
Summary: Polynomial Fitting
polyfit

Fits a polynomial to data.

polyval

Evaluates a polynomial at specified locations.

Simple fitting
Fit polynomial to data. c = polyfit(x,y,n);

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

Fitting with centering and scaling


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

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


Summary: User Interaction

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

You can use inputdlg to gather input from


the user.

You can use disp to show output on the disp('Message')


command window. Message

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.

The expression contains an expression that evaluates to a value. switch


expression
case
value_1

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

Always end the expression with the keyword end end

Here is an example.

Define x in the workspace. x = 2;

Run the switch-case code. switch x


case 1
disp('x is 1')
case 2
disp('x is 2')
otherwise
disp('x is neither
1 nor 2')
end
The output shows that the statements in the case x is 2
where x==2 are executed.

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,
code_e
in else is executed.

Always end the expression with the keyword end end

Evaluate expression to return a value. switch


expression
case
value 1

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

Always end the expression with the keyword end end

Summary: Determining Size

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

Use numel to find the total number of elements in an array of any N = numel(prices)


dimension. N =
190

Summary: Creating and Calling Functions


Define a function Call a function

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

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

You might also like