Matlab & Simulink Advanced Programming

Fundamental Courses

MATLAB Fundamental
Virtual 1950 USD /500 USD (2021)

VDO สอนตอนที่ 1 โดย ผศ.ดร.กิตติพงษ์ เยาวาจา (1-2 ชม/ เรียนรู้ทดลอง 3 ชม)
VDO สอนตอนที่ 2 โดย ผศ.ดร.กิตติพงษ์ เยาวาจา (1-2 ชม/ เรียนรู้ทดลอง 3 ชม)
VDO สอนตอนที่ 3 โดย ผศ.ดร.กิตติพงษ์ เยาวาจา (1-2 ชม/ เรียนรู้ทดลอง 3 ชม)
VDO สอนตอนที่ 4 โดย ผศ.ดร.กิตติพงษ์ เยาวาจา (1-2 ชม/ เรียนรู้ทดลอง 3 ชม)
VDO สอนตอนที่ 5 โดย ผศ.ดร.กิตติพงษ์ เยาวาจา (1-2 ชม/ เรียนรู้ทดลอง 3 ชม)
VDO สอนตอนที่ 6 โดย ผศ.ดร.กิตติพงษ์ เยาวาจา (1-2 ชม/ เรียนรู้ทดลอง 3 ชม)
VDO สอนตอนที่ 7 โดย ผศ.ดร.กิตติพงษ์ เยาวาจา (1-2 ชม/ เรียนรู้ทดลอง 3 ชม)

Course Description
Modules
Course Quick Reference
Getting Started
Overview of the course. Entering MATLAB commands, importing and saving data, and using the MATLAB documentation.

Lessons:
Course Overview
Entering Commands
Getting Data into MATLAB
Obtaining Help
The MATLAB Editor
Summary of Getting Started
Plotting and Common Modifications70 min100%
Create plots of vector data. Modify, annotate, and export plots.

Lessons:
Course Example – Visualizing Gasoline Prices
Plotting
Annotating Plots
Axis Control
Exporting Figures
Summary of Plotting
Working with Live Scripts45 min100%
Create, use, format, and share live scripts.

Lessons:
Course Example – Using a Script to Automate Plotting Gasoline Prices
Create and Run a Script
Code Sections
Comments and Text
Sharing Live Scripts
Summary of Live Scripts
Creating and Manipulating Arrays140 min100%
Create, combine, and reshape arrays.

Lessons:
Course Example – Arrays of Data
Manually Entering Arrays
Creating Evenly-Spaced Vectors
Concatenating Arrays
Array Creation Functions
Reshaping Arrays
Summary of Creating and Manipulating Arrays

Accessing Data in Arrays60 min94%
Extract subsets of arrays, and modify elements in an array.

Lessons
Course Example – Accessing Data in Arrays
Accessing Data in Vectors
Accessing Data in Matrices
Summary of Accessing Data in Arrays
Mathematical and Statistical Operations with Arrays120 min100%
Use arrays as mathematical objects or as collections of (vector) data. Understand the appropriate use of MATLAB to distinguish between these applications.

Lessons:
Course Example – Electricity Consumption
Performing Operations on Arrays
Calculating Statistics of Vectors
Using Statistical Operations on Matrices
Matrix Multiplication
Summary of Operations with Arrays
Visualizing Data in 2D and 3D105 min100%
Identify and use plot types for 2D and 3D visualization. Modify plot properties.

Lessons:
Identifying Available Vector Plot Types
Annotating with Multiple Strings of Text
Customizing Plot Properties
Plotting Multiple Columns
Visualizing Matrices
Summary of Visualizing Data in 2D and 3D
Conditional Data Selection90 min100%
Extract and analyze subsets of data that satisfy given criteria.

Lessons:
Course Example – Home Field Advantage
Logical Operations and Variables
Counting Elements
Logical Indexing
Summary of Conditional Data Selection
Review Project I5 min100%
Tie together several topics covered in the course

Lessons:
Project – Halfway Review of Fundamentals
Tables of Data125 min100%
Import data as a MATLAB table. Work with data stored as a table.

Lessons:
Course Example – Storing Premier League Data
Storing Data in a Table
Sorting Table Data
Extracting Portions of a Table
Extracting Data from a Table
Exporting Tables
Summary of Tables of Data
Organizing Data145 min100%
Store data in relevant data types. Operate on the data types.

Lessons:
Course Example – Premier League Team Information
Combining Tables
Table Properties
Indexing into Cell Arrays
Working with Dates and Times
Operating on Dates and Times
Representing Discrete Categories
Summary of Organizing Data

Preprocessing Data85 min5%
Perform typical data preprocessing tasks in MATLAB, including normalizing data and dealing with missing data.

Lessons:
Course Example – Preprocessing Electricity Usage Data
Normalizing Data
Working with Missing Data
Interpolating Missing Data
Summary of Preprocessing Data
Common Data Analysis Techniques85 min
Perform common data analysis tasks in MATLAB, including smoothing data and fitting polynomials.

Lessons:
Course Example – Analyzing Electricity Consumption
Moving Window Operations
Linear Correlation
Polynomial Fitting
Summary of Common Data Analysis Techniques
Programming Constructs170 min
Create flexible code that can interact with the user, make decisions, and adapt to different situations.

Lessons:
Course Example – Comparing Prices
User Interaction
Decision Branching
Determining Size
For Loops
While Loops
Summary of Programming Constructs
Increasing Automation with Functions90 min
Increase automation by encapsulating modular tasks as user-defined functions. Understand how MATLAB resolves references to files and variables.

Lessons:
Course Example – Electricity Consumption in Different Sectors
Creating and Calling Functions
Function Files
Workspaces
MATLAB Path and Calling Precedence
Summary of Functions
Troubleshooting Code35 min
Explore MATLAB tools for debugging and measuring code performance.

Lessons:
Course Example – Debugging
Code Analyzer
Debugging Run-Time Errors
Summary of Troubleshooting Code
Review Project II15 min
Tie together several topics covered in the course

Lessons:
Project – Review of Fundamentals
Conclusion5 min
Learn next steps and give feedback on the course.

Lessons:
Additional Resources
Survey

MATLAB Fundamentals

Working with the MATLAB User InterfaceObjective: Become familiar with the main features of the MATLAB integrated design environment and its user interfaces. Get an overview of course themes.Reading data from filesSaving and loading variablesPlotting dataCustomizing plotsExporting graphics for use in other applications
Variables and CommandsObjective: Enter MATLAB commands, with an emphasis on creating variables, accessing and manipulating data in variables, and creating basic visualizations. Collect MATLAB commands into scripts for ease of reproduction and experimentation.Entering commandsCreating numeric and character variablesMaking and annotating plotsGetting helpCreating and running live scripts
Analysis and Visualization with VectorsObjective: Perform mathematical and statistical calculations with vectors. Use MATLAB syntax to perform calculations on whole data sets with a single command. Organize scripts into logical sections for development, maintenance, and publishing.Performing calculations with vectorsAccessing and modifying values in vectorsFormatting and sharing live scripts
Analysis and Visualization with MatricesObjective: Use matrices as mathematical objects or as collections of (vector) data. Understand the appropriate use of MATLAB syntax to distinguish between these applications.Creating and manipulating matricesPerforming calculations with matricesCalculating statistics with matrix dataVisualizing matrix data
Tables of DataObjective: Import data as a MATLAB table. Work with data stored as a table.Storing data as a tableOperating on tablesExtracting data from tablesModifying tables
Conditional Data SelectionObjective: Extract and analyze subsets of data that satisfy given criteria.Logical operations and variablesFinding and countingLogical indexing
Organizing DataObjective: Organize table data for analysis. Represent data using appropriate native MATLAB data types.Combining tables of dataTable metadataDates and durationsDiscrete categories
Analyzing DataObjective: Perform typical data analysis tasks in MATLAB, including importing data from files, preprocessing data, fitting a model to data, and creating a customized visualization of the model.Importing from spreadsheets and delimited text filesDealing with missing dataPlotting functionsCustomizing plots
Increasing Automation with Programming ConstructsObjective: Create flexible code that can interact with the user, make decisions, and adapt to different situations.Programming constructsUser interactionDecision branchingLoops
Increasing Automation with FunctionsObjective: Increase automation by encapsulating modular tasks as user-defined functions. Understand how MATLAB resolves references to files and variables. Use MATLAB development tools to find and correct problems with code.Creating functionsCalling functionsSetting the MATLAB pathDebuggingUsing breakpointsCreating and using structures

ค่าเรียน MATLAB for Data Processing and Visualization Virtual 750 USD /200 USD (2021)

Importing DataObjective: Read text files that contain a mixture of data types, delimiters, and headers.Import a mixture of data types from arbitrarily formatted text filesImport only required columns of data from a text fileImport and merge data from multiple files
Processing DataObjective: Process raw imported data by extracting, manipulating, aggregating, and counting portions of data.Process data with missing elementsCreate and modify categorical arraysAggregate, bin, and count groups of data
Customizing VisualizationsObjective: Annotate and modify standard plots to produce informative customized graphics.Determine properties of graphics objects and their associated valuesLocate and manipulate graphics objectsCustomize plots by modifying properties of graphics objects
Working with Irregular DataObjective: Import and visualize scattered data from text files with irregular formatting.Parse text files to determine formattingImport data from separate sections of a text fileExtract data from container variablesInterpolate irregularly spaced three-dimensional dataVisualize three-dimensional data in two and three dimensions

Further study
https://www.mathworks.com/matlabcentral/answers/
https://www.mathworks.com/matlabcentral/fileexchange/
https://www.mathworks.com/help/index.html
https://www.mathworks.com/content/dam/mathworks/fact-sheet/matlab-basic-functions-reference.pdf
https://www.mathworks.com/services/training/courses.html

1. Getting Started

Summary: Getting Started

Creating Variables

Modifying Variables

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

Cleaning Up

clearClears variables from the workspace.clcClears the Command Window and moves the cursor to the upper left corner of the window.

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.

Creates myData.mat containing current workspace variables.save myData
Instead of saving the entire MATLAB workspace, you can selectively save individual variables. Saves x and y to someFile.mat.save someFile x y
Loads variables from myData.mat into current workspace.load myData

saveSaves workspace variables to a MAT-file.loadLoads variables from a MAT-file into the workspace.

Obtaining Help

You can access the documentation with the doc function at the command line or from the toolstrip.

three ways to access the documentationYou can filter search results by product and type of page.

search resultsDocumentation pages for functions have information organized with increasing levels of detail.

anatomy of function documentation


2. Plotting and Common Modifications

Summary: Plotting and Common Modifications

Here, the plot function plots Germany against Year.plot(Year,Germany)Plot of Germany Against Year

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”.
plot(Australia,Germany,”mo”)Plot of Germany Against Australia

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

hold on and hold off

Annotating Plots

Textual information can be added to plots using separate annotation functions. All of these functions take text input.
titleAdd title to plotxlabelLabel the x-axisylabelLabel the y-axislegendAdd legend to plot
Grid lines can be added or removed to plots.
gridDisplay axes grid lines

Example

title("Gasoline Prices")
xlabel("Year")
ylabel("Price (USD/L)")
legend("Germany","Australia","Mexico",...
    "Location","northwest")
grid on

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
            

Exporting a Figure

You can either copy and paste output or export a figure as an image file.

copy and paste a figure


3. Working with Live Scripts

Summary: Working with Live Scripts

Create and Run a Script

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

CreateRun

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.

code sections in live editorYou can run and add code sections in the Section section of the Live Editor tab in the toolstrip.

Comments and Text

To insert a line of text, click the Text button in the Text section of the Live Editor tab in the MATLAB Toolstrip.

Format the text using the formatting options provided in the Text section.

Comments

To create a comment, add comment where you want to add more information.

load 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, Word, HTML, and LaTeX.


4. Creating and Manipulating Arrays

Summary: Creating and Manipulating Arrays

Manually Entering Arrays

Create a Row Vector

Use square brackets and separate the values using a comma or a space. 

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. 

b = [2;3;5;7]

b =
     2
     3
     5
     7

Transpose a Vector

Use the transpose operator 

'

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. 

A = [1 3 5;2 4 6]

A =
     1  3  5
     2  4  6

Creating Evenly-Spaced Vectors

Given the Start Value, End Value, and Interval

Use the colon operator to separate the starting value, interval, and the ending value. 

a = 3:2:7

a =
     3  5  7

When Interval is 1

Use the colon operator to separate the starting and the ending value. 

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. 

c = linspace(3.2,8.1,5)

c =
     3.2  4.42  5.65  6.87  8.1

Concatenating Arrays

Horizontal Concatenation

horizontal concatenation using a spaceSeparate elements using a comma (,) or space (  )

Vertical Concatenation

vertical concatenation using a semicolonSeparate elements using a semicolon (;)

Combined Concatenation

vertical and horizontal concatenationCreate each row separating elements with a comma (,) or space (  ), then separate the rows with a semicolon (;)

Array Creation Functions

Several functions exist that allow you to create arrays.

       

Most of these functions support the calling syntaxes shown below.

Calling syntaxOutput
fun(m,n)m-by-n
fun(n)n-by-n

Reshaping Arrays

The following column of information is reshaped into a matrix.

reshaping indexes

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

5. Accessing Data in Arrays

Summary: Accessing Data in Arrays

Indexing into Vectors

vector indexing

Indexing into Matrices

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


6. Mathematical and Statistical Operations with Arrays

Summary: Mathematical and Statistical Operations with Arrays

Performing Operations on Arrays

There are many operators that behave in element-wise manner, i.e., the operation is performed on each element of the array individually.

Mathematical Functions

Other Similar Functions
sinSine
cosCosine
logLogarithm
roundRounding Operation
sqrtSquare Root
modModulus
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.

Calculating Statistics of Vectors

Common Statistical Functions

FunctionDescription
minReturns the minimum element
maxReturns the maximum element
meanReturns the average of the elements
medianReturns the median value of the elements

Using min and max

min with 2 outputs

Ignoring NaNs

When using statistical functions, you can ignore NaN values

  avg = mean(v,"omitnan")

Statistical Operations on Matrices

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

FunctionBehavior
maxLargest elements
minSmallest elements
meanAverage or mean value
medianMedian value
modeMost frequent values
stdStandard deviation
varVariance
sumSum of elements
prodProduct 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.
cols and rows

>> M = mean(A,dim)
MVector of average values along dimension dim.
AMatrix
dimDimension across which the mean is taken.
1: the mean of each column
2: the mean of each row

Matrix Multiplication

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

inner dimensions
outer dimensions

Solving Systems of Linear Equations

ExpressionInterpretation
x = B/ASolves x*A = B (for x)
x = A\BSolves A*x = B (for x)

7. Visualizing Data in 2D and 3D

Summary: Visualizing Data in 2D and 3D

Identifying Available Plot Types

FunctionDescription
scatterScatter plot, with variable marker size and color
barBar graph (vertical and horizontal)
stemDiscrete sequence (signal) plot
stairsStairstep graph
areaFilled area plot
piePie chart
histogramHistogram

See the complete list of all available plots here.

Annotating with Multiple Strings of Text

Arrays of strings are useful for annotating visualizations. Use square brackets, [], with spaces and semicolons, ; to create a string array the same way you create a numeric matrix.

        x = ["hello" "sweet";"peaceful" "world"]
        x =
            2×2 string array
            "hello"      "sweet"
            "peaceful"   "world"
    

xticksSets tick locations along the x-axis.xticklabelsLabels the x-axis ticks.xtickangleRotates the x-axis tick labels.

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 ("m")yellow ("y")cyan ("c")white ("w")

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

Plotting Multiple Columns

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

plotting each month separately

Visualizing Matrices

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

z is a 5-by-5 matrixzz = 0 0 0 0 0 0 0 -6 0 0 0 -3 1 3 0 0 0 8 1 0 0 0 0 0 0
The surf function plots each point z(j,k) over the point x=k and y=jsurf(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 zThe number of elements of y must match the number of rows of zx = 11:15; y = 21:25; surf(x,y,z)

8. Conditional Data Selection

Summary: Conditional Data Selection

Logical Operations and Variables

Relational Operators

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

Logical Operators

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

Counting Elements

PurposeFunctionOutput
Are any of the elements true?anytrue/false
Are all the elements true?alltrue/false
How many elements are true?nnzdouble
What are the indices of the elements that are true?finddouble

Logical Indexing

Purpose: Select the elements of an array based on certain criteria. x and y
Step 1: Create a logical vector by evaluating the given condition.

Example:

  idx = x > 4

x and y
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
z = y(idx)
orz = y(x > 4)
  

x and y


9. Review Project I


10. Tables of Data

Summary: Tables of Data

Storing Data in a Table

The readtable function creates a table in MATLAB from a data file.EPL = readtable(“EPLresults.xlsx”,”TextType”,”string”);
The table function can create a table from workspace variables.teamWinsTable = table(team,wins)teamWins = Team Wins ___________________ ____ “Arsenal” 20 “Chelsea” 12 “Leicester City” 23 “Manchester United” 19
The array2table function can convert a numeric array to a table. The VariableNames property can be specified as a cell array of names to include as variable names in the table.stats = array2table(wdl, … “VariableNames”,[“Wins” “Draws” “Losses”])stats = Wins Draws Losses ____ _____ ______ 20 11 7 12 14 12 23 12 3 19 9 10

Sorting Table Data

The sortrows function sorts the data in ascending order, by default.EPL = sortrows(EPL,”HomeWins”);
Use the optional "descend" parameter to sort the list in descending order.EPL = sortrows(EPL,”HomeWins”,”descend”);
You can also sort on multiple variables, in order, by specifying a cell array of variable names.EPL = sortrows(EPL,[“HomeWins” “AwayWins”],”descend”);
You can also show summary statistics for variables in a table.summary(EPL)

Extracting Portions of a Table

Display the original table.EPLEPL = Team HW HD HL AW AD AL ___________________ __ __ __ __ __ __ “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 “Chelsea” 5 9 5 7 5 7 “Bournemouth” 5 5 9 6 4 9 “Aston Villa” 2 5 12 1 3 15
Inside parenthesis, specify the row numbers of the observations and column numbers of the table variables you would like to select.EPL(2:4,[1 2 5])ans = Team HW AW ___________________ __ __ “Arsenal” 12 8 “Manchester City” 12 7 “Manchester United” 12 7
You may also use the name of the variable for indexing.

If you want to reference more than one variable, use a cell array containing the variable names.
EPL(2:4,[“Team” “HW” “AW”])ans = Team HW AW ___________________ __ __ “Arsenal” 12 8 “Manchester City” 12 7 “Manchester United” 12 7

Extracting Data from a Table

Display the original table.EPLEPL = Team HW HD HL AW AD AL ___________________ __ __ __ __ __ __ “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
You can use dot notation to extract data for use in calculations or plotting.tw = EPL.HW + EPL.AWtw = 23 20 19 19
You can also use dot notation to create new variables in a table.EPL.TW = EPL.HW + EPL.AWEPL = 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
If you want to extract multiple variables, you can do this using curly braces.draws = EPL{:,[“HD” “AD”]}draws = 6 6 4 7 2 7 5 4

Exporting Tables

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

   writetable(tableName,"myFile.txt","Delimeter","\t")
    

The file format is based on the file extension, such as .txt.csv, or .xlsx , but you can also specify a delimeter.
writetableWrite a table to a file.


11. Organizing Data

Summary: Organizing Data

Combining Tables

Display the original tables.EPLEPL = Team Points ___________________ ______ “Leicester City” 81 “Arsenal” 71 “Aston Villa” 17gamesgames = Wins ____ 23 20 3teamInfoteamInfo = Team Manager ________________ _________________ “Arsenal” “Arsène Wenger” “Aston Villa” “Eric Black” “Leicester City” “Claudio Ranieri”
You can concatenate tables that are the same length but do not share a common variable.[EPL games]ans = Team Points Wins ________________ ______ ____ “Leicester City” 81 23 “Arsenal” 71 20 “Aston Villa” 17 3
The join function can combine tables with a common variable.EPL = join(EPL,teamInfo)EPL = Team Points Manager ___________________ ______ ___________________ “Leicester City” 81 “Claudio Ranieri” “Arsenal” 71 “Arsène Wenger” “Aston Villa” 17 “Eric Black”

Table Properties

Display the table properties.EPL.Propertiesans = Table Properties with properties: Description: ” UserData: [] DimensionNames: {‘Row’ ‘Variable’} VariableNames: {1×11 cell} VariableDescriptions: {1×11 cell} VariableUnits: {} VariableContinuity: [] RowNames: {} CustomProperties: No custom properties are set.
You can access an individual property of Properties using dot notation.EPL.Properties.VariableNamesans = 1×11 cell array Columns 1 through 4 {‘Team’} {‘HomeWins’} {‘HomeDraws’} {‘HomeLosses’} Columns 5 through 8 {‘HomeGF’} {‘HomeGA’} {‘AwayWins’} {‘AwayDraws’} Columns 9 through 11 {‘AwayLosses’} {‘AwayGF’} {‘AwayGA’}

Indexing into Cell Arrays

determining size

The variable varNames is a cell array that contains character arrays of different lengths in each cell.varNames = teamInfo.Properties.VariableNames'Team''Payroll_M__''Manager''ManagerHireDate'
Using parentheses to index produces a cell array, not the character array inside the cell.varName(2)'Payroll_M__'
In order to extract the contents inside the cell, you should index using curly braces, { }.varName{2}’Payroll_M__’
Using curly braces allows you to rename the variable.varName{2} = ‘Payroll’'Team''Payroll''Manager''ManagerHireDate'

Working with Dates and Times

Dates are often automatically detected and brought in as datetime arrays.teamInfoans = Manager ManagerHireDate _________________ _______________ “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
Many functions operate on datetime arrays directly, such as sortrows.sortrows(teamInfo,”ManagerHireDate”)ans = Manager ManagerHireDate _________________ _______________ “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 numeric inputs. The first input is year, then month, then day.t = datetime(1977,12,13)t = 13-Dec-1977
To create a vector, you can specify an array as input to the datetime function.ts = datetime([1903;1969],[12;7],[17;20])ts = 17-Dec-1903 20-Jul-1969

Operating on Dates and Times

Create datetime variables to work with.seasonStart = datetime(2015,8,8)seasonStart = 08-Aug-2015 seasonEnd = datetime(2016,5,17)seasonEnd = 17-May-2016
Use subtraction to produce a duration variable.seasonLength = seasonEnd – seasonStartseasonLength = 6792:00:00
Functions such as years and days can help make better sense of the output.seasonLength = days(seasonLength)seasonLength = 283
They can also create durations from a numeric value.seconds(5)ans = 5 seconds
Use the between function to produce a context-dependent calendarDuration variable.seasonLength = between(seasonStart,seasonEnd)seasonLength = 9mo 9d
Create a calendar duration from a numeric input with functions such as calmonths and calyears.calmonths(2)ans = 2mo

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

Representing Discrete Categories

x is a string array.x = [“C” “B” “C” “A” “B” “A” “C”];x = “C” “B” “C” “A” “B” “A” “C”
You can convert x into a categorical array, y, using the categorical function.y = categorical(x);y = C B C A B A C
You can use == to create a logical array, and count elements using nnz.nnz(x == “C”)ans = 3
You can view category statistics using the summary function.summary(y) A B C 2 2 3
You can view combine categories using the mergecats function.y = mergecats(y,[“B” “C”],”D”)y = D D D A D A D

12. Preprocessing Data

Summary: Preprocessing Data

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


normalizeNormalize data using a specified normalization method.

Working with Missing Data

Data contains missing values, in the form of both -999 and NaN.x = [2 NaN 5 3 -999 4 NaN];
The ismissing function identifies only the NaN elements by default.ismissing(x)ans = 1×7 logical array 0 1 0 0 0 0 1
Specifying the set of missing values ensures that ismissing identifies all the missing elements.ismissing(x,[-999,NaN])ans = 1×7 logical array 0 1 0 0 1 0 1
Use the standardizeMissing function to convert all missing values to NaN.xNaN = standardizeMissing(x,-999)xNaN = 2 NaN 5 3 NaN 4 NaN
Ignores NaNs by default
(default flag is "omitnan")
Includes NaNs by default
(default flag is "includenan")
max
min
cov
mean
median
std
var
Data TypeMeaning of “Missing”
double
single
NaN
string arrayEmpty string (<missing>)
datetimeNaT
duration
calendarDuration
NaN
categorical<undefined>

Interpolating Missing Data

fillmissingFills missing values of an array or table.

Interpolation assuming equal spacing of observations.z = fillmissing(y,”method”)
Interpolation with given observation locations.z = fillmissing(y,”method”,”SamplePoints”,x)
MethodMeaning
"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: Common Data Analysis Techniques

Moving Window Operations

movminMoving minimum
movmaxMoving maximum
movsumMoving sum
movmeanMoving mean
movmedianMoving median
movstdMoving standard deviation
movvarMoving variance
Mean calculated with a centered moving k-point window.z = movmean(y,k)
Mean calculated with a moving window with kb points backward and kf points forward from the current point.z = movmean(y,[kb kf])

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 multiple series together.yyaxis left plot(…) yyaxis right plot(…)
Plot variables against each other.plotmatrix(data)
Calculate linear correlation coefficients.corrcoef(data)ans = 1.0000 0.8243 0.1300 0.9519 0.8243 1.0000 0.1590 0.9268 0.1300 0.1590 1.0000 0.2938 0.9519 0.9268 0.2938 1.0000

Polynomial Fitting

polyfitFits a polynomial to data.polyvalEvaluates 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);

14. Programming Constructs

Summary: Programming Constructs

User Interaction

functions for user interactions

You can use inputdlg to gather input from the user.ctry = inputdlg(“Enter a country:”);inputdlg prompt
You can use disp to show output on the command window.disp(“Message”)Message
You can use warning and error as well.warning(“Missing data”)Warning: Missing dataerror(“Missing data”)Missing data
The msgboxerrordlg, and warndlg functions can display messages to the user.msgbox(“Analysis complete”)msgbox

Decision Branching

The condition_1 is evaluated as true or false.if condition_1
If condition_1 is true, then the code_1 code block is executed.code_1
Otherwise, the next case is tested. There can be any number of cases.elseif condition_2 code_2 elseif condition_3 code_3
If none of the cases are a match, then the code, code_e, in else is executed.else code_e
Always end the expression with the keyword endend
Evaluate expression to return a value.switch expression
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 1 code_1 case value 2 code_2
If none of the cases are a match, then the code, code_3, in otherwise is executed. The otherwise block is optional.otherwise code_3
Always end the expression with the keyword endend

Determining Size

determining size

Use size to find the dimensions of a matrix.s = size(prices)s = 19 10 [m,n] = size(prices)m = 19 n = 10 m = size(prices,1)m = 19 n = size(prices,2)n = 10
Use length when working with vectors where one of the dimensions returned by size is 1.m = length(Year)m = 19
Use numel to find the total number of elements in an array of any dimension.N = numel(prices)N = 190

For Loops

The index is defined as a vector. Note the use of the colon syntax to define the values that the index will take.for index = first:increment:last code end

While Loops

The condition is a variable or expression that evaluates to true or false. While condition is truecode executes. Once condition becomes false, the loop ceases execution.while condition code end

15. Increasing Automation with Functions

Summary: Increasing Automation with Functions

Creating and Calling Functions

Define a functionCall a function
x and yx and y

Function Files

Function TypeFunction Visibility
Local functions:
Functions that are defined within a script.      
Visible only within the file where they are defined.
Functions:
Functions that are defined in separate files.
Visible to other script and function files.

Workspaces

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

a = 42; b = foo(a);
transfer
foo.mlxfunction y = foo(x)    a = sin(x);    x = x + 1;    b = sin(x);    y = a*b;end

Base Workspace   a  42  b  0.7623
 
Function Workspace  a  -0.9165  b  -0.8318  x  43  y  0.7623

MATLAB Path and Calling Precedence

In MATLAB, there are rules for interpreting any named item. These rules are referred to as the function precedence order. Most of the common reference conflicts can be resolved using the following order:

  1. Variables
  2. Functions defined in the current script
  3. Files in the current folder
  4. Files on MATLAB search path

A more comprehensive list can be found here.

The search path, or path is a subset of all the folders in the file system. MATLAB can access all files in the folders on the search path.
To add folders to the search path:

  1. On the Home tab, in the Environment section, click Set Path.
  2. Add a single folder or a set of folders using the buttons highlighted below.

search path screenshot


16. Troubleshooting Code

Summary: Troubleshooting Code

Code Analyzer

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

IconMeaning
There is a potential for unexpected results or poor code performance.
There are syntax errors that must be addressed.

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.


17. Review Project II


18. Conclusion

Pages: 1 2 3 4 5

Create Account



Log In Your Account