Thailand Excellence Community
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 Interface | Objective: 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 Commands | Objective: 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 Vectors | Objective: 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 Matrices | Objective: 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 Data | Objective: 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 Selection | Objective: Extract and analyze subsets of data that satisfy given criteria.Logical operations and variablesFinding and countingLogical indexing |
| Organizing Data | Objective: Organize table data for analysis. Represent data using appropriate native MATLAB data types.Combining tables of dataTable metadataDates and durationsDiscrete categories |
| Analyzing Data | Objective: 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 Constructs | Objective: Create flexible code that can interact with the user, make decisions, and adapt to different situations.Programming constructsUser interactionDecision branchingLoops |
| Increasing Automation with Functions | Objective: 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 Data | Objective: 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 Data | Objective: 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 Visualizations | Objective: 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 Data | Objective: 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




| You can use the Up (↑) and Down (↓) arrows on the keyboard to scroll through previous commands. |
clearClears variables from the workspace.clcClears 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.
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.
You can access the documentation with the doc function at the command line or from the toolstrip.
You can filter search results by product and type of page.
Documentation pages for functions have information organized with increasing levels of detail.
Here, the plot function plots Germany against Year. | plot(Year,Germany) | |
| 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”) |
The hold on command allows you to plot multiple data sets together on the same axes.
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
title("Gasoline Prices")
xlabel("Year")
ylabel("Price (USD/L)")
legend("Germany","Australia","Mexico",...
"Location","northwest")
grid on
v = axis
v =
0 12 0.1 0.9

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

axis tight

You can either copy and paste output or export a figure as an image file.
Use the controls in the MATLAB toolstrip to create and run scripts.
| Create | Run |
|---|
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 run and add code sections in the Section section of the Live Editor tab in the toolstrip.
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.
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;
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.
Use square brackets and separate the values using a comma or a space.
a = [10 15 20 25]
a =
10 15 20 25
Use square brackets and separate the values using a semi-colon.
b = [2;3;5;7]
b =
2
3
5
7
Use the transpose operator
'
.
c = b'
c =
2 3 5 7
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
Use the colon operator to separate the starting value, interval, and the ending value.
a = 3:2:7
a =
3 5 7
Use the colon operator to separate the starting and the ending value.
b = 3:7
b =
3 4 5 6 7
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
Separate elements using a comma (,) or space ( )
Separate elements using a semicolon (;)
Create each row separating elements with a comma (,) or space ( ), then separate the rows with a semicolon (;)
Several functions exist that allow you to create arrays.


Most of these functions support the calling syntaxes shown below.
| Calling syntax | Output |
|---|---|
fun(m,n) | |
fun(n) |
The following column of information is reshaped into a matrix.
| 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,[]); |
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)
output = M(2,3)
M
output = M(2,[3 4])
M
output = M(2,2:4)
M
output = M(2,:)
M
There are many operators that behave in element-wise manner, i.e., the operation is performed on each element of the array individually.

| Other Similar Functions | |
|---|---|
sin | Sine |
cos | Cosine |
log | Logarithm |
round | Rounding Operation |
sqrt | Square Root |
mod | Modulus |
| Many more |

| Operators | |
|---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
^ | Exponentiation |

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

| 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.
| 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 |
min and maxWhen using statistical functions, you can ignore NaN values
avg = mean(v,"omitnan")
Some common mathematical functions which calculate a value for each column in a matrix include:
| Function | Behavior |
|---|---|
max | Largest elements |
min | Smallest elements |
mean | Average or mean value |
median | Median value |
mode | Most frequent values |
std | Standard deviation |
var | Variance |
sum | Sum of elements |
prod | Product of elements |
| A = [8 2 4 ; 3 2 6 ; 7 5 3 ; 7 10 8] A = 8 2 4 3 2 6 7 5 3 7 10 8 | ||
| Amax = max(A) Amax = 8 10 8 | ||
| Astd = std(A) Astd = 2.2174 3.7749 2.2174 | ||
| Asum = sum(A) Asum = 25 19 21 |
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. |
A | Matrix |
dim | Dimension across which the mean is taken.1: the mean of each column2: the mean of each row |
Matrix multiplication requires that the inner dimensions agree. The resultant matrix has the outer dimensions.
| Expression | Interpretation |
|---|---|
| x = B/A | Solves x*A = B (for x) |
| x = A\B | Solves A*x = B (for x) |
| 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.
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.
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
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.
You can use the plot function on a matrix to plot each column as a separate line in your plot.
You can use visualization functions to plot your three-dimensional data.
z is a 5-by-5 matrix | zz = 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=j | surf(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 z | x = 11:15; y = 21:25; surf(x,y,z) |
== | 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
& | 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
| 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 |
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 = x > 4 z = y(idx) | or | z = y(x > 4) |
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 |
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) |
| 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 |
| 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 |
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.
| 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” |
| 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’} |
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' |
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 |
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
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 |
normalizeNormalize data using a specified normalization method.
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") |
|---|---|
maxmin | covmeanmedianstdvar |
| Data Type | Meaning of “Missing” |
|---|---|
doublesingle | NaN |
string array | Empty string (<missing>) |
datetime | NaT |
durationcalendarDuration | NaN |
categorical | <undefined> |
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) |
| 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. |
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 backward and kf points forward from the current point. | z = movmean(y,[kb kf]) |
You can investigate relationships between variables visually and computationally:
yyaxis to add another vertical axis to allow for different scales.plotmatrix to create an array of scatter plots.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 |
polyfitFits a polynomial to data.polyvalEvaluates a polynomial at specified locations.
| Fit polynomial to data. | c = polyfit(x,y,n); | |
| Evaluate fitted polynomial. | yfit = polyval(c,xfit); |
| Fit polynomial to data. | [c,~,scl] = polyfit(x,y,n); | |
| Evaluate fitted polynomial. | yfit = polyval(c,xfit,[],scl); |
You can use inputdlg to gather input from the user. | ctry = inputdlg(“Enter a country:”); | |
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 msgbox, errordlg, and warndlg functions can display messages to the user. | msgbox(“Analysis complete”) |
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 end | end |
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 end | end |
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 |
| 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 |
The condition is a variable or expression that evaluates to true or false. While condition is true, code executes. Once condition becomes false, the loop ceases execution. | while condition code end |
| Define a function | Call a function |
|---|---|
| Function Type | Function 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. |
A function maintains its own workspace to store variables created in the function body.
| a = 42; b = foo(a); | foo.mlxfunction y = foo(x) a = sin(x); x = x + 1; b = sin(x); y = a*b;end | |
Base Workspace | Function Workspace |
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:
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:
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. |
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.