Docsity

Matlab Basics Summary, Schemes and Mind Maps of Matlab skills

Toggle sidebar
bg1
22/10/2023, 2:35 PMMATLAB Fundamentals - Quick Reference
Page 11 of 37https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html
Many statistical functions accept an optional dimensional argument that specifies whether the
operation should be applied to columns independently (the default) or to rows.
Matrix Multiplication
Matrix multiplication requires that the inner dimensions agree. The resultant matrix has the outer dimensions.
Solving Systems of Linear Equations
Expression Interpretation
x = B/ASolves x*A = B (for x)
x = A\BSolves A*x = B (for x)
Visualizing Data in 2D and 3D
Summary of Visualizing Data in 2D and 3D
>> M = mean((((A,dim))))
Outputs
MVector of average values along
dimension dim .
Inputs
AMatrix
dim Dimension across which the mean
is taken.
1: the mean of each column
2: the mean of each row
22/10/2023, 2:35 PMMATLAB Fundamentals - Quick Reference
Page 12 of 37https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html
Summary: Visualizing Data in 2D and 3D
Identifying Available Plot Types
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
>> scatter((((x,y,n,c,filled))))
Inputs
xx-data
yy-data
nmarker size
ccolor
filled If provided, markers
will be filled in disks.
Otherwise, they are
circles.
See the complete list of all available plots here.
Customizing Annotations
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 stringstringstringstring array
"hello" "sweet"
"peaceful" "world"
You can use markup in your labels.
ylabel(((("\pi r^2"))))
xticks Sets tick locations along the x-axis.
xticklabels Labels the x-axis ticks.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe

Partial preview of the text

Download Matlab Basics Summary and more Schemes and Mind Maps Matlab skills in PDF only on Docsity!

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

Matrix Multiplication

Matrix multiplication requires that the inner dimensions agree. The resultant matrix has the outer dimensions. Solving Systems of Linear Equations Expression Interpretation x = B/A Solves xA = B (for x ) x = A\B Solves Ax = B (for x )

Visualizing Data in 2D and 3D

Summary of Visualizing Data in 2D and 3D

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

Summary: Visualizing Data in 2D and 3D

Identifying Available Plot Types

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

scatter((((x,y,n,c,filled)))) Inputs x x -data y y -data n marker size c color filled If provided, markers will be filled in disks. Otherwise, they are circles. See the complete list of all available plots here.

Customizing Annotations

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 stringstringstringstring array "hello" "sweet" "peaceful" "world" You can use markup in your labels. ylabel(((("\pi r^2")))) xticks Sets tick locations along the x-axis. xticklabels Labels the x-axis ticks.

xtickangle Rotates the x-axis tick labels.

Customizing Plot Properties

Specifying Property Values

See the complete list of line specifications here: https://www.mathworks.com/help/matlab/ref/plot.html#btzitot_sep_mw_3a76f056- 2882-44d7-8e73-c695c0c54ca8. 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.

Axis Control

Get Axes Limits v = axis v = 0 12 0.1 0. plot((((x,y,linespec, Property1, Value1, Property2, Value2, Property3, Value3,...)))) Custom Axis Limits xlim([([([([-1 13 ])])])]) ylim([([([([-1 2 ])])])]) Axis Limits = Data Range axis tight

Plotting Multiple Columns

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

The readtable function creates a table in MATLAB from a data file. How many elements are true? nnz double What are the indices of the elements that are true? (^) find double

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

Tables of Data

Summary of Tables of Data

Summary: Tables of Data

Storing Data in a Table

EPL = readtable(((("EPLresults.xlsx","TextType","string")))); teamWinsTable = table((((team,wins)))) The table function can create a table from workspace variables. The array2table function can convert a numeric array to a table. The VariableNames property can be specified as a string array of names to include as variable names in the table. The sortrows function sorts the data in ascending order, by default. Use the optional "descend" parameter to sort the list in descending order. You can also sort on multiple variables, in order, by specifying a string array of variable names. You can also show summary statistics for variables in a table. Display the original table. teamWins = TeamTeamTeamTeam WinsWinsWinsWins


"Arsenal" 20 "Chelsea" 12 "Leicester City" 23 "Manchester United" 19 stats = array2table((((wdl, ... "VariableNames",[[[["Wins" "Draws" "Losses"])])])]) stats = WinsWinsWinsWins DrawsDrawsDrawsDraws LossesLossesLossesLosses


20 11 7 12 14 12 23 12 3 19 9 10

Sorting Table Data

EPL = sortrows((((EPL,"HomeWins")))); EPL = sortrows((((EPL,"HomeWins","descend")))); EPL = sortrows((((EPL,[[[["HomeWins" "AwayWins"]]]],"descend")))); summary((((EPL))))

Extracting Portions of a Table

EPL

EPL =

TeamTeamTeamTeam HWHWHWHW HDHDHDHD HLHLHLHL AWAWAWAW ADADADAD ALALALAL


"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. You may also use the name of the variable for indexing. If you want to reference more than one variable, use a string array containing the variable names. Display the original table. You can use dot notation to extract data for use in calculations or plotting. You can also use dot notation to create new variables in a table. If you want to extract multiple variables, you can do this using curly braces.

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

ans = TeamTeamTeamTeam HWHWHWHW AWAWAWAW


"Arsenal" 12 8 "Manchester City" 12 7 "Manchester United" 12 7 EPL(((( 2 : 4 ,[[[["Team" "HW" "AW"])])])]) ans = TeamTeamTeamTeam HWHWHWHW AWAWAWAW


"Arsenal" 12 8 "Manchester City" 12 7 "Manchester United" 12 7

Extracting Data from a Table

EPL

EPL =

TeamTeamTeamTeam HWHWHWHW HDHDHDHD HLHLHLHL AWAWAWAW ADADADAD ALALALAL


"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 = 23 20 19 19 EPL.TW = EPL.HW + EPL.AW EPL = TeamTeamTeamTeam HWHWHWHW HDHDHDHD HLHLHLHL AWAWAWAW ADADADAD ALALALAL TWTWTWTW


"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 = 6 6 4 7 2 7 5 4 Specify row indices to extract specific rows. draws13 = EPL{[{[{[{[ 1 3 ]]]],[[[["HD" "AD"]}]}]}]} draws = 6 6 2 7

Exporting Tables

You can use the writetable function to create a file from a table. writetable(((( tableName,"myFile.txt","Delimiter","\t")))) The file format is based on the file extension, such as .txt , .csv , or .xlsx , but you can also specify a delimiter. writetable Write a table to a file.

Organizing Tabular Data

Summary of Organizing Tabular Data

Summary: Organizing Tabular Data

Combining Tables

If the tables are already aligned so that the rows correspond to the same observation, you can concatenate them with square brackets. [[[[teamInfo games]]]] teamInfo games Leicester Arsenal Tottenham Manchester City Manchester United If the tables are not already aligned so that the rows correspond to the same observation, you can still combine the data by merging them with a join.

Dates are often automatically detected and brought in as datetime arrays. Many functions operate on datetime arrays directly, such as sortrows. You can create a datetime array using numeric inputs. The first input is year, then month, then day. To create a vector, you can specify an array as input to the datetime function. Create datetime variables to work with. Use subtraction to produce a duration variable. Functions such as years and days can help make better sense of the output. They can also create durations from a numeric value. Use the between function to produce a context- ans = ManagerManagerManagerManager ManagerHireDateManagerHireDateManagerHireDateManagerHireDate


"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 = ManagerManagerManagerManager ManagerHireDateManagerHireDateManagerHireDateManagerHireDate


"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 t = datetime(((( 1977 , 12 , 13 )))) t = 13 - Dec- ts = datetime([([([([ 1903 ; 1969 ]]]],[[[[ 12 ; 7 ]]]],[[[[ 17 ; 20 ])])])]) ts = 17 - Dec- 20 - Jul-

Operating on Dates and Times

seasonStart = datetime(((( 2015 , 8 , 8 )))) seasonStart = 08 - Aug- seasonEnd = datetime(((( 2016 , 5 , 17 )))) seasonEnd = 17 - May- seasonLength = seasonEnd - seasonStart seasonLength = 6792 : 00 : 00 seasonLength = days((((seasonLength)))) seasonLength = 283 seconds(((( 5 )))) ans = 5 seconds seasonLength = between((((seasonStart,seasonEnd)))) Use the between function to produce a context- dependent calendarDuration variable. Create a calendar duration from a numeric input with functions such as calmonths and calyears. x is a string array. You can convert x into a categorical array, y , using the categorical function. You can use == to create a logical array, and count elements using nnz. You can view category statistics using the summary function. You can view combine categories using the mergecats function. Normalize the columns of a matrix using z-scores. seasonLength = 9 mo 9 d calmonths(((( 2 )))) ans = 2 mo You can learn more about datetime and duration functions in the documentation. Create Date and Time Arrays

Representing Discrete Categories

x = [[[["C" "B" "C" "A" "B" "A" "C"]]]]; x = "C" "B" "C" "A" "B" "A" "C" y = categorical((((x)))); y = C B C A B A C nnz((((x == "C")))) ans = 3 summary((((y)))) AAAA BBBB CCCC 2 2 3 y = mergecats((((y,[[[["B" "C"]]]],"D")))) y = D D D A D A D

Preprocessing Data

Summary of Preprocessing Data

Summary: Preprocessing Data

Normalizing Data

normalize Normalize data using a specified normalization method. xNorm = normalize((((x))))

Center the mean of the columns in a matrix on zero. Scale the columns of a matrix by the first element of each column. Stretch or compress the data in each column of a matrix into a specified interval. Data contains missing values, in the form of both -999 and NaN. The ismissing function identifies only the NaN elements by default. Specifying the set of missing values ensures that ismissing identifies all the xNorm = normalize((((x,"center","mean")))) xNorm = normalize((((x,"scale","first")))) xNorm = normalize((((x,"range",[[[[a b])])])])

Working with Missing Data

Any calculation involving NaN results in NaN. There are three ways to work around this, each with advantages and disadvantages: Ignore missing data when performing calculations. Maintains the integrity of the data but can be difficult to implement for involved calculations. Remove missing data. Simple but, to keep observations aligned, must remove entire rows of the matrix where any data is missing, resulting in a loss of valid data. Replace missing data. Keeps the data aligned and makes further computation straightforward, but modifies the data to include values that were not actually measured or observed. The Clean Missing Data task can be used to remove or interpolate missing data. You can add one to a script by selecting it from the Live Editor tab in the toolstrip. LIVE EDITOR

Task

x = [[[[ 2 NaN 5 3 -999 4 NaN]]]]; ismissing((((x)))) ans = 1 × 7 logicallogicallogicallogical array 0 1 0 0 0 0 1 ismissing((((x,[[[[-999,NaN])])])]) missing elements. Use the standardizeMissing function to convert all missing values to NaN. Use the rmmissing function to remove missing values. Interpolation assuming equal spacing of observations. Interpolation with given observation locations. ans = 1 × 7 logicallogicallogicallogical array 0 1 0 0 1 0 1 xNaN = standardizeMissing((((x,-999)))) xNaN = 2 NaN 5 3 NaN 4 NaN cleanX = rmmissing((((xNaN)))) cleanX = 2 5 3 4 Ignores NaNNaNNaNNaN s by default (default flag is "omitnan""omitnan""omitnan""omitnan" ) Includes NaNNaNNaNNaN s by default (default flag is "includenan""includenan""includenan""includenan" ) max min cov mean median std var Data Type Meaning of "Missing" doubledoubledoubledouble singlesinglesinglesingle NaN string array Empty string ( ) datetime NaT duration calendarDuration NaN categorical

Interpolating Missing Data

fillmissing Fills missing values of an array or table. z = fillmissing((((y,"method")))) z = fillmissing((((y,"method","SamplePoints",x)))) Method Meaning "next" The missing value is the same as the next nonmissing value in the data.

Fit polynomial to data. Evaluate fitted polynomial. Fit polynomial to data. Evaluate fitted polynomial. You can add a live control to get input from the user. You can use disp to show output on the command window. You can use warning and error as well. c = polyfit((((x,y,n)))); yfit = polyval((((c,xfit)))); Fitting with centering and scaling [[[[c,~,scl]]]] = polyfit((((x,y,n)))); yfit = polyval((((c,xfit,[][][][],scl))));

Programming Constructs

Summary of Programming Constructs

Summary: Programming Constructs

User Interaction

disp(((("Message")))) Message warning(((("Missing data")))) Warning: Missing data error(((("Missing data")))) Missing data msgbox(((("Analysis complete")))) The msgbox , errordlg , and warndlg functions can display messages to the user. The condition_1 is evaluated as true or false. If condition_1 is true , then the code_1 code block is executed. Otherwise, the next case is tested. There can be any number of cases. If none of the cases are a match, then the code, code_e , in elseelseelseelse is executed. Always end the expression with the keyword endendendend Evaluate expression to return a value. If expression equals value_1 , then code_1 is executed. Otherwise, the next case is tested. There can be any number of cases. If none of the cases are a match, then the code, code_3 , in otherwiseotherwiseotherwiseotherwise is executed. The otherwiseotherwiseotherwiseotherwise block is optional. Always end the expression with the keyword endendendend

Decision Branching

ifififif condition_ code_ elseifelseifelseifelseif condition_ code_ elseifelseifelseifelseif condition_ code_ elseelseelseelse code_e endendendend switchswitchswitchswitch expression casecasecasecase value 1 code_ casecasecasecase value 2 code_ otherwiseotherwiseotherwiseotherwise code_ endendendend

Determining Size

Use size to find the dimensions of a matrix. Use length when working with vectors where one of the dimensions returned by size is 1. Use numel to find the total number of elements in an array of any dimension. The index is defined as a vector. Note the use of the colon syntax to define the values that the index will take. The condition is a variable or expression that evaluates to true or 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 m = length((((Year)))) m = 19 N = numel((((prices)))) N = 190

For Loops

forforforfor index = first:increment:last code endendendend

While Loops

false. While condition is true , code executes. Once condition becomes false, the loop ceases execution. whilewhilewhilewhile condition code endendendend

Increasing Automation with Functions

Summary of Functions

Summary: Increasing Automation with Functions

Creating and Calling Functions

Define a function Call a function

Function Files

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.

Workspaces

A function maintains its own workspace to store variables created in the function body. a = 42 ; b = foo((((a))));

  1. functionfunctionfunctionfunction y = foo((((x))))
  2. a = sin((((x))));
  3. x = x + 1 ;
  4. b = sin((((x))));
  5. y = a*b;
  6. endendendend Base Workspace Function Workspace foo.mlx

After you fix the error, the code in line 1 is no longer red and underlined. The corresponding indicator line goes away. There is still one syntax error left, though. You should fix all syntax errors flagged by the Code Analyzer before running your script or function. Icon Meaning There is a potential for unexpected results or poor code performance. There are syntax errors that must be addressed. The Code Analyzer identifies both syntax errors and warnings.

Inspecting Variables

Runtime errors are bugs that aren't syntax errors. Run time errors can produce an execution-stopping error or just be something you didn't mean to do. An effective way to troubleshoot them is to inspect variables. Remove semicolons to inspect the output. Mouse over a variable to see its size and a preview. Click on a variable to view each place where the variable is used, created, or modified. Click the gray indicator lines in the Code Analyzer to go directly to the line where a variable is used. Look at the variables in the Workspace for a preview. Double click them to inspect elements in the Variable Editor.

Stepping Through Code

When variables change throughout a script, you can step through your code to inspect intermediate values. You can run section by section or set breakpoints. Run and Advance You can run scripts section by section. In the Section section of the Live Editor tab in the Toolstrip, you can break up your code into sections to run one at a time. This is the current section. Section Break : Add a section break to create a code section. Run and Advance : Run code in the current section, then move to the next section.

MATLAB Fundamentals - Quick Reference 22/10/2023, 2:35 PM https://matlabacademy-content.mathworks.com/4.56/R2023a/content/quick-reference/mlbe_quick_reference.html Page 37 of 37 Setting Breakpoints You can also set breakpoints in scripts and functions to stop code execution before specific lines. This works particularly well with functions, where you otherwise don't have access to the workspace. Breakpoints give you access to the same tools you have in scripts for inspecting variables. Add breakpoints by clicking line numbers. Continue : Run code until the next breakpoint (or the end of the script). Step : Run only the next line of code. Stop : Stop code execution and exit debug mode. Don't forget to clear your breakpoints and save your work!

A Debugging Workflow

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.