Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
60 views
37 pages
Códigos MatLAb
Uploaded by
Pedro Odorizzi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save Códigos MatLAb For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
60 views
37 pages
Códigos MatLAb
Uploaded by
Pedro Odorizzi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Carousel Previous
Carousel Next
Download
Save
Save Códigos MatLAb For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 37
Search
Fullscreen
‘a10ei2022 10:56 MATLAB Fundament - Quick Reference MATLAB Fundamentals 1. Introduction 2. Using the MATLAB Desktop Summary: Working with Live Scripts Create and Run a Script Use the controls in the MATLAB toolstrip to create and run scripts, create oF Run [> Code Sections Cade 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 toolstip. LIVE EDITOR iS Section Break Run and Advance Run ft, Erm ton Iitps:Imatabacademyy.mathworks.convartfacts/quickreference.html ?course-mibesrelease=R2021b8language=en& 197‘ayosr2022 10:55, Quick Reference: Comments and Text ‘To insert a line of text, click the LS] Text button in the Text section ofthe Live Editor tab in the MATLAB Toolstip. Format the text using the formatting options provided in the Text section, Normal BIUM rer Comments To create a comment, add ¥ comment where you want to add more information. load gcosts X Converts from US$/gal to US$/L gal2lit = @.2642; x conversion factor Germany = gal2lit*Germany; australia = gal2lit*australia; Mexico = gal2lit*Mexico; Exporting Live Script Files la Save You can export your live script and results using the Save button in the Live Editor tab. ‘Available formats include POF, Word, HTML, and = Latex. fe Save Save As. Export to POF Export to Word HTML. Latex Hie Dae Export Folder. 3. Creating and Manipulating Arrays Summary: Creating and Manipulating Arrays Manually Entering Arrays Iitps:Imattabacademyy.mathworks.convartfacts/quickreference.html ?course-mibeBrelease=R2021b8language=en& 27‘a1082022 10:56, Quick Reference: Create a Row Vector Use square brackets and separate the values a= [10 15 20 25) Using a comma or a space. 10 15 20 25 Create a Column Vector Use square brackets and separate the values b= [2535537] using a semi-colon. be 2 3 5 7 ‘Transpose a Vector Use the transpose operator * ced 2357 Create a Matrix Use square brackets and enter values row-bytow. = = (13 552 4 6) Separate values in a row using a comma or a space, and use a semicolon to start a new row. Ae 13 246 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, 357 When Interval is 4 Use the colon operator to separate the starting bea and the ending value. b 34567 Given the Start Value, End Value, and Number of Elements Iitps:imattabacademy.mathworks.convartifacts/quickreference.html ?course=mibeBrelease=R202b8language=en& 37‘a1082022 10:56, MATLAB Fundamentals - Quick Reference Use the function Linspace when the number of ¢ = Linspace(3.2,8.2,5) elements in the vector are known 3.2 4.42 5.65 6.87 8.2 Concatenating Arrays Horizontal Concatenation si parate elements using a somma (,) or space ( ) Vertical Concatenation sea] = ‘Separate elements using a semicolon (;) Combined Coneatenation jemn oma] = Create each row separating elements with a comma (,) or space ( ), then separate the rows with a semicolon (:) Array Creation Functions. hitps:simatlabacademy.mathworks.convarfactsiquick reference. html ?course=mbbeBrelease=R2021b8language=en& 407‘a1082022 10:56, Several functions exist that allow you to create arrays. A = fun(m,n); —_— - Quick Reference SSS, = =— | eye rand m gallery randn hadamard rosser | hankel toeplitz hilb vander invhilb wilkinson magic zeros ones Most of these functions support the caling syntaxes shown below, cating | Output syntax pmo) — B mya san Fe} Reshaping Arrays ‘The following column of information is reshaped into a matrix, 2.646 reshape (x,5,52) 2.624 2.886 2.495 2.518 2.400 2.303 2. 6d6 | 2.400 2.161 vis Sais 2.624 | 2.303 044 oe 2.586 | 2.161 083 2.495 | 2.318 2.108 128 Sama 2.518 | 2.134 143 fa pa rand(260,1); Iitps:imattabacademy.mathworks.convartifacts/quickreference.html ?course=mibeBrelease=R202b8language=en& 507‘a1082022 10:56, Quick Reference: y = reshape(,5,52) 5 ‘Specify the dimensions for the new array reshape(x,5, [15 For convenience, you can also leave one of the dimensions blank y etx S411) when calling reshave and that dimension will be calculated automatically 4. Accessing Data in Arrays Summary: Accessing Data in Arrays Indexing 1203 4 1 [2s 1 | 15] 14 | 26 fos 2|rs 2 |1s|24 far fia 3 | 13 3 | 2s] 16 | 19 | o7 4 | os 4 faa] at] rs | as 5 | 13 5 | 19| 28 | os | os ov ™ wea) Extract one element from a vector 1s viend) Extract the last element from a vector 13 Extract multiple elements from a vector When you are extracting elements of a matrix you need to provide two indices, the row and column numbers, Iitps:imattabacademy.mathworks.convartfacts/quickreference.html ?course-mibeBrelease=R2021b8language=en& 207‘a10ei2022 10:56 Quick Reference: Extract one element from a matrix M(:,end) a9 Extract an entire column, Here, itis the last one. a 07 2.5 0.6 [2 end],2) Extract multiple elements from a matrix. aa 2.8 Changing Elements in Arrays vey 2.3 Change one element from a vector é 1.3 a 1.3 vena) e ‘Change multiple element of a vector to the same value ° e a9 1.3 v3) = B87) Change multiple element of a vector to different values hitpssimalabacacmy.mathworks.convartfactsiquick reference.html ?eourse Ibe8release=R2021bslanguage=en8& 707‘a1082022 10:56, - Quick Reference via) = 42 3 5 7 ‘Assign a non-existent value oo 1.3 e e e 42 =u as Remove elements from a vector 13 e e e 2 Changing elements in matrices works the same way as with vectors, but you must specify both rows and columns. 5. 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, ie, the operation is performed on each element of the array individually Mathematical Functions Other Similar Functions sin Sine sin( )|sin( ) sor _|Posine ee TE sin( )lsin( > log Logerttm sin( )\sin( ) round Rounding Operation sqrt Square Root mod Modulus Many more Iitps:imattabacademy.mathworks.convartifacts/quickreference.html ?course=mibeBrelease=R202b8language=en& 807‘a1082022 10:56, Matrix Operations (Including Scalar Expansion) MATLAB Fundament +O +|+ +/+) 4+ Element-wise Operations + +\+)+ +\+)+ Implicit Expansion a + = +)4)+ +\+)+ Quick Reference: Operators Adeition Subtraction Multiplication Division Exponentiation (Matrix exponentiation) Operators Addition ‘Subtraction Elomentwise Multiplication Elementwise Division Element-wise Exponentiation Operators ‘Adeition Subtraction Elementwise Multiplication Elomentwise Division Element-wise Exponentiation ‘Array operations can be performed on operands of diferent compatibe sizes. Two arrays have compatible sizes ifthe size of each Calculating Statistics of Vectors Common Statistical Functions dimension is ether the same or one. Function Description ain Retums the minimum element max Returns the maximum element mean Retums the average ofthe elements median Returns the median value of the elements, hitpssimalabacacmy.mathworks.convartfactsiquick reference.html ?eourse Ibe8release=R2021bslanguage=en8& 907‘a1082022 10:56, Quick Reference: Using min and max Ignoring NaNs ‘When using statistical functions, you can ignore NaN values avg = nean(v, "onitnan") Statistical Operations on Matrices Some common mathematical functions which q=[824;326;753;37 108) calculate @ value for each column in @ matrix A include: 8 2 4 Funetion Behavior 32 6 7 5803 ax Largest elements "9 7 2 8 min Smallest elements mean Average or mean snax = max(A) value sax = median Median value 8 w 8 mode Most frequent values std Standard doviation asta = seacay var Variance Astd = sun Sumof elements 2.2174 3.7749 2.274 prod Product of elements |Asun = sum(A) asun = 2 19 on hitps:imalabacacmy.mathworks.convatfactsiquick reference.html ?eourse Ibe8release=R2021bslanguage=en8& 10937‘a1082022 10:56, MATLAB Fundament - Quick Reference Many statistical functions accept an optional dimensional argument that specifies whether the operation should be applied to columns independently (the default) or to rows. yyy Dimension = 1 Dimension = 2 >> M = mean(A,dim) Outputs Inputs Vector of average values along A Matrix dimension din dim | Dimension 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, Ho = = & mby@)—9—>-OPy- mby-p B-H-B Solving Systems of Linear Equations Expression _ Interpretation X= B/A Solves x4 = 8 (for x) X= A\B Solves Atx = 8 (for x) 6. Visualizing Data in 2D and 3D Summary: Visualizing Data in 2D and 3D Iitps:sImattabacademyy.mathworks.convartfacts/quickreference.html ?course-mibe&release=R2021b8language=en& wer‘a1082022 10:56, MATLAB Fundamentals - Quick Reference Identifying Available Plot Types Function Description scatter Scatter plot, wih variable marker size and color bar Bar graph (vertical and horizontal) stem Discrete sequence (signal) plot stairs Sterstep graph area Filled area plot pie Pie chart histogram Histogram >> seatter(x,y,n,c, filled) Inputs x data y | yedata a marker size « color Filled | If provided, markers willbe filed in disks. Otherwise, they are circles. See the complete list ofall 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. world" 2x2 string array hello’ ‘sweet peaceful” “world” ylabel("\pi r*2") You can use markup in your labels. xticks Sets tick locations along the x-axis, xticklabels Labels the x-axis ticks. xtickangle Rotates the x-axis tick labols. Iitps:imattabacademy.mathworks.convartifacts/quickreference.html ?course=mibeBrelease=R202b8language=en& 12097‘a1082022 10:56, Quick Reference: Customizing Plot Properties Speci 1g Property Values plot (x,y,linespec, Property, Valuet ,Property2, Value2,Property3,Value3,...) See the complete list of line specifications here: hilos:/Avww.mathworks.com/help/matlab/ret/inespec.himl Common line properties to modify ‘+ “Linewiath” (Width of the line and marker edges) + "MarkerSize" (size of the marker symbols) + "MarkerEdgeColor” (color of the edge of the marker symbols) + "MarkerFaceColor™ (color ofthe interior of the marker symbols) + “color” (color of the lin, particularly wnen given as RGB values) ‘MATLAB Line Properties reference Specifying Colors red ("r") green (“g blue ( magenta ("nm") yellow ("y") cyan ( Oras.avector [R G 8] where each value is from 0 to 1 Axis Control Got Axes Limits e 2 01 09 hitpssimalabacacmy.mathworks.convartfactsiquick reference.html ?eourse Ibe8release=R2021bslanguage=en8& 13097‘a10ei2022 10:56 - Quick Reference Custom Axis Limits xlin({-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. plot(x,Y) nplots H... Revenue [SUS] a mby-n = Ho Iitps:Imattabacademyy.mathworks.convartfacts/quickreference.html ?course-mibeBrelease=R2021b8language=en& 14037‘a10ei2022 10:56 hitps:imalabacacmy.mathworks.convatfactsiquick reference.html ?oourse Visualizing Matrices ‘You can use visualization functions to plot your three-dimensional data, z is a S-by-5 matrix ‘The surf function plots z(j,k) over the point x=k and y=j ‘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 2 + The number of elements of y must match the number of rows, of 2 Exporting a Figure ‘You can either copy and paste output or export a figure as an image file, MATLAB Fundamentals - Quick Reference surf(z) Soar surt(x.ys2) Ibe8release=R2021bslanguage=en8& 19937‘a1082022 10:56, " ii af = Australia | - Germany So | Lat Mexico 2 a Bs 2 a4 8 83 a 2 1 1990 1995 2000 Year 7. 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 Logical Operators ® AND I oR - Nor Counting Elements Purpose ‘Are any of the elements true? ‘Ave all the elements true? How many elements are true? v= (67891; we [24826]; NE=veew Ne = [6789]; [24816]; Wow a>” eer Funetion Output any true/false all trueffaise noz double Iitps:Imatabacademyy.mathworks.convartfacts/quickreference.html ?course-mibesrelease=R2021b8language=en& 2005 16837‘a1082022 10:56, MATLAB Fundament Purpose Function Output, What are the indices of the elements that are true? find Logical Indexing criteria Stop 1: Create a logical vector by evaluating the given condition. Example: idx =x >4 Stop 2: Use the logical vector as an index into another array to extract the elements corresponding to the true values. Example: Ades x>4 gz y(x> 4) 2 = y(idx) 8. Review Project | 9. Tables of Data Summary: Tables of Data Storing Data in a Table The readtable function creates 2 table in MATLAB from a data file. Cui Retro double 5 7 3 1 1 4 7 3 x y 5 tue] [7 3 false] [a 1lx>a4| false] [4 7 ‘true 3 x y 5 true bel 7 NK 3 faise} [a] “[7 1|x>a|faise| [4 3 7 me Pa x yo8 readtable("EPLresults.xisx", "TextType", "string"; Iitps:Imattabacademyy.mathworks.convartfacts/quickreference.html ?course-mibeBrelease=R2021b8language=en& 87‘a1082022 10:56, The table function can create a table from workspace variables. The array2table function can convert a numeric array to a table, The Variablevanes property can be specified as a string array of names to include as variable names in the table, Sorting Table Data 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 sot on multiple variables, in order, by specifying a string array of variable names. You can also show summary statistics for variables in a table. 1g Portions of a Table Quick Reference: teaniinsTable = table(tean,wins) teankins = Team Wins arsenal” 2 ‘chelsea! 2 eicester City’ 2B tanchester United” 19 stats = array2table(wdl, . 'VariableNanes",["Wins" "Draws" "Losses"]) stats = Wins Draws Losses ~@ ou 7 2 4 2 3 2 3 19 9 1 EPL EPL = sortrous(EPL, "HoneWins","“descend”); EPL = sortrows(EPL,["Homewins" "AwayWins"], descend”); sunmary(EPL) Iitps:Imattabacademyy.mathworks.convartfacts/quickreference.html ?course-mibeBrelease=R2021b8language=en& 1893718/08/2022 10:56 MATLAB Fundamentals - Quick Reference EPL eet Team Hw HD HL AW ADL Leicester City" m 6 1 n 6 2 Display the original table. arsenal Bees Manchester City m2 5 7 7 5 "Manchester United” 12 5 2-7 8 ‘Chelsea 5 9 5 7 5 7 sournenouth* 5 5 9 6 4 9 “aston Villa" 205 2 1 3 35 EPL(2:4, [2 2 51) Inside parenthesis, specify the Tear he AW row numbers ofthe — = - observations and column 2s numbers of the table variables, manchester City" = 127 Yyou would lke to select. Manchester United” 327 EPL(2:4, ["Tean* “Hi “AW"]) You may also use the name of ans the variable for indexing. Team Hw AW IF you want to reference more ‘Arsenal pa than one variable, use a string Manchester City’ nw o7 array containing the variable Manchester United” 127 \g Data from a Table eet eet Tean Hw HD HL AW ADL Display the original table. —- = - -5=- c pe an 6 2 ‘Arsenal p44 3 8 7 4 Manchester City’ mo2 5 7 7 5 “Manchester united” 12 5 9-2-7 8 tw = EPL. + EPL.AW You can use dot notation to we oxiac data or vse » catsatons orth oii * ® Iitps:Imattabacademyy.mathworks.convartfacts/quickreference.html ?course-mibeBrelease=R2021b8language=en& 19037‘a1082022 10:56, 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. Specily row indices to extract specific rows, Exporting Tables Quick Reference: EPL.TW = EPL.HW + EPL.AW EPL = Team WW HD HL AW DAL eleester City m6 1 nu 6 2 ‘Arsenal’ m4 3 8 7 4 fanchester city" mo2 8 7 7 8 Manchester United” 12 5 2 7 4 8 draws = EPL{:,[°HD" "AD"]} rans = draws13 = EPL({2 3],["HO" "AD"]} rans = 6 6 207 ‘You can use the weitetable function to create a file from a table, writetable(tabLenane, “nyFile.txt","Delimeter”,"\t") ‘The file format is based on the fle extension, such as .txt, .csv, or .x1sx_, but you can also specify a delimeter. weltetable Write a table toa fil. 10. 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] hitps:imalabacacmy.mathworks.convatfactsiquick reference.html ?eourse Ibe8release=R2021bslanguage=en8& 2 20 Fey » 20837‘a10ei2022 10:56 = ae Biteantnto EE omnes If the tables are not already aligned so that the rows correspond to the same observation, you can stil combine the data by merging them with ajoin. 1 "Nex Mogae 6 1 2 eg Rapa é x 2 3 Rose Lavelet 3 a [EB uswntrop3 Position “Rose Lavelle” “midfielder” “Alex Morgan’ “forward” “Megan Rapinoe” "orward” [EB postop3 ‘top3 = join(usuntTop3, posTop3) tops = Player The join function can combine tables with a common variable, Rose Lavelle’ Table Properties EPL.Properties Description Userbata Display the table properties, VariableNanes: VariableDescriptions: variableunits: Vardablecontinuity RowNanes: CustomProperties. hitpssimalabacacmy.mathworks.convartfactsiquick reference.html ?eourse DimensionNanes: Ibe8release=R2021bslanguage=en8& Goals Position 6 “forward” 6 “Forward” “niafielder” Table Properties with properties u {'Row’ ‘Variable') {aaai cell) (at cell} oO a oO No custom properties are set. 21137‘a10ei2022 10:56 You can access an individual properly of Properties using dot notation, The variable varNanes is @ cell array that contains character arrays of diferent Tengths in each cell Using parentheses to index. produces a cell array, not the character array inside the cell In order to extract the contents inside the cell, you should index using curly braces, { } Using curly braces allows you to rename the variable. 11. Specialized Data Types MATLAB Fundamentals - Quick Reference EPL. Properties. VariableNanes dell cell array Columns 1 through 4 {'Tean'} — {Homeliins'} _{"HomeDraws'} _{ 'HoneLosses"} Columns 5 through & {CHoneGF"} —{'HomeGA'}—(“Awaykins'}—{“AwayDraws") Columns 8 through 11 Chwaylosses'} — {‘AwayGF"}—_{“AwayGA") varWane{2} “Payroll varNane{2} = "Payroll" Payroll. Manager NanagerHiireDate Summary: Specialized Data Types Iitps:Imattabacademyy.mathworks.convartfacts/quickreference.html ?course-mibeBrelease=R2021b8language=en& 22087‘a1082022 10:56, Working with Dates and Times Dates are often automatically detected and brought in as datetine arrays, Many functions operate on datetime arrays directly such as sortrows You can create a datetine array using numeric inputs. The first input is year, then month, then day. To create a vector, you can specify an array as input tothe datetime function, Operating on Dates and Times Create datetine 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. Quick Reference: ‘teaninfo Manager ManagerttireDate Rafael Benitez" 3/11/2016 ‘Claudio Ranieri" 7/13/2015 Ronald Koenan’ 6/16/2014 “David Unsworth" 5/12/2016 ‘Slaven Bilié® 6/9/2015 sortrows (teantnfo, "ManagerHirebate") Manager ManagerHireDate Ronald Koenan’ 6/16/2014 ‘Slaven Bilt 6/9/2015 ‘Claudio Ranieri" 7/13/2015 Rafael Benitez" 3/11/2016 "pavid Unsworth” 5/32/2016 t = datetine(1977,12,13) te 13-Dec-1977 ts = datetine({1903;1969], [1257], [17;26]) ts = 17-Dec-1903 20-Jul-1968 seasonstart = datetine(2@15,8,8) seasonstart = 08-Aug-2015 seasonénd = datetine(2036,5,27) seasontnd 17-May-2016 seasonLength = seasonEnd - seasonStart seasonLength = 6792:@0:00 seasonLength = days(seasonLength) seasonLength = 283 Iitps:Imattabacademyy.mathworks.convartfacts/quickreference.html ?course-mibeBrelease=R2021b8language=en& 23037‘a1082022 10:56, They can also create durations from a numeric value. Use the between function to produce a context- dependent calendarDuration variable. Create a calendar duration from a numeric input with functions such as calwonths and calyears, MATLAB Fundament Quick Reference: seconds(5) 5 seconds seasonLength = between(seasonstart, seasonénd) seasonLength = 9m 9d calmontns(2) 2n0 You can learn more about datetime and duration functions in the documentation. ‘Create Dale and Time Arrays Representing Discrete Categories x isa 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 You can view category statistics using the summary function You can view combine categories using the margacats function. 12. Preprocessing Data Summary: Preprocessing Data Normalizing Data co " ca y y cB Cc A 8B A 3 summary(y) A a oc 2 2 y= mergecats(y, ["8' ye > po Dl normalize Normalize data using a specified normalization method, hitps:imalabacacmy.mathworks.convatfactsiquick reference.html ?eourse Ibe8release=R202"bslanguage=en8& 24037‘a10ei2022 10:56 Normalize the columns of a matrix using 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. Working with Missing Data Quick Reference: xNorm = normalize(x) xNorm = norealize(x,"center", xNorm = normalize(x,"scale","first") xNorm = norealize(x,"range",[2 6]) ‘The Clean Missing Data task can be used to remove or interpolate missing data. You can add one to a script by selecting Itfrom the Live Editor tab in the toolstip. LVE EDITOR: Data contains missing values, in the form of both -999 and NaN. ‘The ismissing function identifies only the NaN elements by defaut Specitying the set of missing values ensures that ismissing identifies all the missing elements. Use the standardizeMicsing function to convert all missing values to Nan x = [2 NaN 5 3-999 4 NaN]; ismissing) 2x7 Logical array @10e080042 ismissing(x,[-999,NaN]) 17 logical array @1eo012102 wan = standareizeMissing(x, -999) xNaN = NN 53 NAN NN Iitps:imattabacademy.mathworks.convartifacts/quickreference.html ?course=mibeBrelease=R202b8language=en& 25037‘a1082022 10:56, MATLAB Fundament Quick Reference: cleanx = rreissing(xNaN) Use the cnmissing function to remove cleanx = missing values. 25 3 4 Ignores NaNs by default Includes NaN's by default (default flag is “onitnan*) (default flag is “includenan’ ste Data Type Meaning of “Missing” double Nan single string array Empty string (
) datetine Nat curation Naw calendarburation categorical
Interpolating Mi ing Data fillnissing Fills missing values of an array or table, 2 = Fillmissing(y, "method Interpolation assuming equal spacing of wy > observations, 2 = Fillmissing(y, "sethod” ,"SamplePoints” x) Interpolation with given observation ey ° ) locations. 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 Iitps:Imattabacademyy.mathworks.convartfacts/quickreference.html ?course-mibeBrelease=R2021b8language=en& 26037‘a1082022 10:56, MATLAB Fundamentals - Quick Reference Method Meaning “pchip" The cubic Hermite interpolating polynomial method forces the interpolant to maintain the same ‘monotonicly as the data. This prevents oscilation between data points. 13. Common Data Analysis Techniques Summary: Common Data Analysis Techniques Moving Window Operations ‘The Smooth Data task can be used to smooth variation or noise in data. You can add one to a script by selecting it from the Live Editor tab in the toolstrp. LUVE EDITOR (=i Task a a ‘The Smooth Data task uses the snoothdata function. 2 = saoothdata(y, "novmean" Mean calculated with a centered moving Kepoint window. 7 = snoothdata(y, "novnean", [kb kf Mean calculated with a moving window % » with kb points backward and kf points forward from the current point, 2 = snoothdata(y,“nownedtan” i Median calculated with a centered moving ” > Kepoint window. 2 = snoothdata(y,"novmedian”, k, "SanplePoints" x Median calculated with a centered moving © ° > Kepoint window using sample points defined in x: 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 conrcoef to calculate pairwise correlations. Iitps:Imattabacademyy.mathworks.convartfacts/quickreference.html ?course-mibeBrelease=R2021b8language=en& 277‘a10ei2022 10:56 MATLAB Fundamentals - Quick Reference yaxis left plot(...) yyaxis ight plot(..-) Plot multiple series together. 4 plotnatrix(data) la wt Be Pets grates hr Te Lae Lm lm lL er corrcoef(data) 1.000 0.8263 @.1300 9.9519 2.8203 1.0000 0.1598 0.9268 0.138 0.1598 1.0008 @,2938 2.9519 0.9268 8.2938 «1.0008 Caleulate linear correlation coefficients. Polynomial Fitting polyfit Fits @ polynomial to data. polyval Evaluates a polynomial at spectied locations. Simple fitting = polyfit(x.yon)s Fit polynomial to data. yfit = polyval(c,xfit) ; Evaluate ited polynomial Fitting with centering and scaling hitpssimalabacacmy.mathworks.convartfactsiquick reference.html ?eourse Ibe8release=R2021bslanguage=en8& 28037‘a10ei2022 10:56 MATLAB Fundamentals - Quick Reference [ey~sel] = polyfit(xysn); Fit polynomial to data. yeit © polyval(e,xfit, [],sel); Evaluate fitted polynomial 14, Programming Constructs Summary: Programming Constructs User Interaction ‘You can add a live control to get input from the user ‘You can use dia to show output on the command window. Message You can use warning and error as well. ‘The msgbox, errondig, and warndlg functions can display Decision Branching disp('Message") warning("Hissing data" Warning: Missing data error(*Missing data") Missing data insgbox("Analysis complete”) messages to the user. Analysis complete Le Iitps:Imattabacademyy.mathworks.convartfacts/quickreference.html ?course-mibeBrelease=R2021b8language=en& 29037‘a10ei2022 10:56 MATLAB Fundamentals ‘The condition 2 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 If none of the cases are a match, then the code, code_e, in else is executed, Always end the expression with the keyword end Evaluate expression to return a value. If expression equals value1, then code1 is executed. Otherwise, the next case is tested. There can be any number of I none of the cases are a match, then the code, code_3, in otherwise is executed. The otherwise block is optional. Always end the expression with the keyword end Quick Reference: Af condition code elseif condition 2 code_2 elseif condition.2 code_3 else code_e end switch expression case value 1 coded case value 2 code_2 otherwise code_3 t-by-n tin} Determining Size m-by-n n-by-1 size (x,2) n 1 length (x) max(m,n) n ; ume (3c) mn hitpssimalabacacmy.mathworks.convartfactsiquick reference.html ?eourse Ibe8release=R2021bslanguage=en8& 3037‘a10ei2022 10:56 Use size to find the dimensions of a matrix. Use length when working with vectors where one of the dimensions retumed by size is 1 Use qunel to find the total number of elements in an array of any dimension, 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, While Loops ‘The condition is a variable or expression that evaluates to true or Quick Reference: size(prices) 2» 10 [n,n] = size(prices) 1e size(prices,1) 1» n= size(prices,2) 18 im = length(vear) 19 numel (prices) 198 for index = first:increnent: Last code end while condition code false. While condition is true, code executes. Once end condition becomes false the loop ceases execution. 15. Increasing Automation with Functions ‘Summary: Increasing Automation with Functions hitpsmatabacademy.mathworks.convarifactsiqick reference hil2course-mlbeBrelease=R202tbélanguage=en& 3107‘910872022 10:50 Quick Reference Creating and Calling Functions Define a function Call afunetion keyword function nome function name function [01,02] = myFunc(41,42) {ot,02] = myFune(i,12) output input output input Function Files Function Type Function Visibility Local functions: Functions that are defined within a sexipt, Visible only within the file where they are defined. Functions: cesta that are defined in separate fies, V'Sile 1 other script and function fle. Workspaces ‘A function maintains its own workspace to store variables created in the function body. fornix 42 . function y = foo(x) a — : sino, foo(a)s —_— KEK ETS 0.7623 be sings abs Base Workspace Function Workspace [Ee 42 fea 09165 [Be 0.7628 Be 08318 fx 2 iy 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 43, Files in the current folder 4, Files on MATLAB search path ‘Amore comprehensive ist can be found here. hitps:imalabacacmy.mathworks.convatfactsiquick reference.html ?eourse Ibe8release=R2021bslanguage=en8& 32897‘a10ei2022 10:56 MATLAB Fundament Quick Reference: ‘The search path, or path is a subset ofall the folders in the fle system. MATLAB can access all files in the folders on the search path, “To add folders to the search path 41. 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. 16. Troubleshooting Code Summary: Troubleshooting Code Code Analyzer Use the MATLAB Code Analyzer. messages shown in the Editor to identify and fix syntax errors. Peiconme #| Define Variables fase ee provictdote'= detetine(218.4,4); agree = —<{_{={ __==["aes8 Import data and fill missing values | ata ~ reaatabtecettenane,“Toxttyse"s “stein S| dates = aetat ats © | usage = detat:s2hs 5 teetan = data Properties vordabiaan(2}; a | | seg sarminctratustec,soiline )y Fit polynomial and predict usage for a future date. © etapseayears = yeara(eates-dotes(t): 10 Ea polytie(clapseateors,ucage degre): 1 endburation = years(precictante-aates()): 12 eager ie = poijval(cselapsdvears): 15 presietesusese = polyval(c,enaurtion ; | Code Analyzer ‘The small red icon at the top of the Code Analyzer, indicates there are errors in the script, Click on it to show red lines identifying the locations of syntax errors, hitps:imalabacacmy.mathworks.convatfactsiquick reference.html ?eourse Ibe8release=R2021bslanguage=en8& 33137‘a10ei2022 10:56 hitps:imalabacacmy.mathworks.convatfactsiquick reference.html ?eourse OueeRefrence © ete Variables j S ( 2) ==—-meee i:) faa He) [eer ° ery Import data and fill missing values eel 10 ata - roustabte(¢tienane,“Tectyoe"s string"): fates ~ ontatssth, sage = catal:s2}5 schon = dats Proportion Varibleiaoe(2]; oage = Fildnissing(usge, seline"); Fit polynomial and predict usage for a future date. © etapeyears = yeara(eates 10 Ea polytie(clapseateors,ucage degre): 1 endburation = years(precictante-aates()): 12 eager ie = poijval(cselapsdvears): 15 presietesusese = polyval(c,enaurtion ; Red indicator lines in the Code Analyzer. identily specific syntax errors, You can mouse over one to see a description of that issue. The first indicator ine describes the mistake you saw in the error message: the closing quotation mark is. missing Clicking an indicator ine puts your cursor where the error was found so you can fix it. Notice thatthe broken portion of the code is red and undertined, | pavhedionmie Define Variables B siatine(2019,2.2)2 Import data and fill missing values ata - roustabte(¢tienane,“Tectyoe"s string"): fates ~ ontatssth, sage = catal:s2}5 schon = dats Proportion Varibleiaoe(2]; ape = fElaniseing(uage, spline"); Fit polynomial and predict usage for a future date. © etapeyears = yeara(eates so ea polytie(eie 1 endburation = years(precictante-aates()): 12 eager ie = poijval(cselapsdvears): 15 presietesusese = polyval(c,enaurtion ; After you fx the error, the code in ine 1 is ne longer red and underlined. The corresponding indicator line goes away. ‘There is still one syntax error let, though. You should fix all syntax errors flagged by the Code Analyzer before running your script or function, leon Meaning A, Theres a potential fr unexpected results or poor code performance @ _ Tere ate syntax errors that must be aderessed, ‘The Code Analyzer identifies both syntax errors and wamings, Inspecting Variables Ibe8release=R2021bslanguage=en8& 407‘a1082022 10:56, MATLAB Fundament Quick Reference: Runtime errors are bugs that aren't syntax errors, Joad elecPrices avgirPrices = priceVr.*dollar2e19 avgElecPrice - mean(aveYrPrices); plot(avgyrPrices) yLine(avgElecbrice)| 0 2 30 Run time ertors can produce an execution-stopping error of just be something you didnt mean to do. An effective way to troubleshoot them is to inspect variables, a load elecPri ea aera auetlecPrice 2 avgvrPrices = priceYr.*dollar2e19; eee a) g Perea rans a Remove semicolons to inspect the output a Joad elecPrices auiewriee « 2 avgirPrices = priceYr.*dollar2e19; hoses, 16SHir. 3 evgelecPrice ~ mean(ave¥oPricéf) aueyrrrices 38.3220 14.7033 14.7736 13.8887 13.5197 -- 35.7262 15.0911 14,6501. 14.2243 13.0002 aT Mouse over a variable to see its size and a preview. a load elecPrices
Continue: Run code until the next breakpoint se (or the end ofthe script) Step: Run only the next ine of code. Stop: Stop code execution and exit debug mode. Dont forget to clear your breakpoints and save your work! ‘A Debugging Workflow hitps:sImatlabacademy.mathworks.convartfacts/quick-eference.himi7course=mibe&release=R2021b8language=en& 3637‘tay08i2022 10:56 MATLAB Fundamentals - Quick Reference When debugging MATLAB code, a common workllow is as follows, Note that after you've identified and fixed any bugs, you should stop your debugging session, save your changes, and ‘lear all breakpoints before running your code again. 17. Review Project Il 18. Conclusion Iitps:Imattabacademyy.mathworks.convartfacts/quickreference.html ?course-mibeBrelease=R2021b8language=en& 3737
You might also like
MATLAB Fundamentals Quick Reference
PDF
No ratings yet
MATLAB Fundamentals Quick Reference
41 pages
MATLAB
PDF
No ratings yet
MATLAB
37 pages
MATLAB Fundamentals Quick Reference
PDF
No ratings yet
MATLAB Fundamentals Quick Reference
43 pages
Matlab 1
PDF
No ratings yet
Matlab 1
90 pages
3 Vectors and Matrices
PDF
No ratings yet
3 Vectors and Matrices
38 pages
Intro Matlab
PDF
No ratings yet
Intro Matlab
34 pages
Lecture 2 - ch2 - Fundamentals
PDF
No ratings yet
Lecture 2 - ch2 - Fundamentals
40 pages
Comm. Sys Lab: SPRING 2013
PDF
No ratings yet
Comm. Sys Lab: SPRING 2013
85 pages
Matlab-Signals and Systems
PDF
No ratings yet
Matlab-Signals and Systems
26 pages
Introduction To Matlab: Luke Dickens
PDF
No ratings yet
Introduction To Matlab: Luke Dickens
41 pages
Introduction To Matlab: Luke Dickens
PDF
No ratings yet
Introduction To Matlab: Luke Dickens
41 pages
L02-Matrices and Arrays
PDF
No ratings yet
L02-Matrices and Arrays
38 pages
Introduction To MATLAB: Sajid Gul Khawaja
PDF
No ratings yet
Introduction To MATLAB: Sajid Gul Khawaja
48 pages
Lab 2 - Overview of MATLAB and Simulink
PDF
No ratings yet
Lab 2 - Overview of MATLAB and Simulink
36 pages
Arrays
PDF
No ratings yet
Arrays
39 pages
Mit Matlab Course
PDF
No ratings yet
Mit Matlab Course
205 pages
Lab 1
PDF
No ratings yet
Lab 1
6 pages
Programming With MATLAB Lab
PDF
No ratings yet
Programming With MATLAB Lab
34 pages
Lesson 2-MSE 360
PDF
No ratings yet
Lesson 2-MSE 360
42 pages
Lecture 2
PDF
No ratings yet
Lecture 2
9 pages
MATLAB Tutorial - 26-07-10
PDF
No ratings yet
MATLAB Tutorial - 26-07-10
9 pages
A Matlab Primer: by Jo Ao Lopes, Vitor Lopes
PDF
No ratings yet
A Matlab Primer: by Jo Ao Lopes, Vitor Lopes
45 pages
Matlab Slides I
PDF
No ratings yet
Matlab Slides I
27 pages
Introduction To Programming: Atlab
PDF
No ratings yet
Introduction To Programming: Atlab
52 pages
Matlab®: Academic Resource Center
PDF
No ratings yet
Matlab®: Academic Resource Center
40 pages
Introduction To Computing - Matlab
PDF
No ratings yet
Introduction To Computing - Matlab
40 pages
Opm 2.M.H.P2
PDF
No ratings yet
Opm 2.M.H.P2
42 pages
MATLAB Fundamentals Quick Reference
PDF
No ratings yet
MATLAB Fundamentals Quick Reference
37 pages
Advancedmatlabtutorialw2012 120903013858 Phpapp02
PDF
No ratings yet
Advancedmatlabtutorialw2012 120903013858 Phpapp02
133 pages
Basic Matlab
PDF
No ratings yet
Basic Matlab
112 pages
Lecture 3 Matrix and Array Operators
PDF
No ratings yet
Lecture 3 Matrix and Array Operators
51 pages
Tutorial Matlab
PDF
No ratings yet
Tutorial Matlab
89 pages
Matlab
PDF
No ratings yet
Matlab
10 pages
Matlab Tutorial - Short
PDF
No ratings yet
Matlab Tutorial - Short
20 pages
Matlab Short Tutorial
PDF
No ratings yet
Matlab Short Tutorial
45 pages
Introduction To Matlab
PDF
No ratings yet
Introduction To Matlab
45 pages
Technical Computing Laboratory Manual
PDF
No ratings yet
Technical Computing Laboratory Manual
54 pages
DIP Lab Intro
PDF
No ratings yet
DIP Lab Intro
65 pages
Introduction To Matlab: Deniz Savas and Mike Griffiths
PDF
No ratings yet
Introduction To Matlab: Deniz Savas and Mike Griffiths
67 pages
MATLAB Introduction: Fortran
PDF
No ratings yet
MATLAB Introduction: Fortran
73 pages
Matlab 1
PDF
No ratings yet
Matlab 1
31 pages
Rob Lab 2
PDF
No ratings yet
Rob Lab 2
19 pages
Introduction To MATLAB: Prepared By: Mahendra Shukla
PDF
No ratings yet
Introduction To MATLAB: Prepared By: Mahendra Shukla
27 pages
Matlabchapter 2
PDF
No ratings yet
Matlabchapter 2
64 pages
Matlab Lecture 6
PDF
No ratings yet
Matlab Lecture 6
70 pages
NM-Lab 03
PDF
No ratings yet
NM-Lab 03
8 pages
476 56518 MVGR Matlab Tutorial
PDF
No ratings yet
476 56518 MVGR Matlab Tutorial
59 pages
Experiment 1 - Fundamental Concepts
PDF
No ratings yet
Experiment 1 - Fundamental Concepts
12 pages
Week 6 C3 Vectors in MATLAB
PDF
No ratings yet
Week 6 C3 Vectors in MATLAB
9 pages
Computer Programming: Introduction To MATLAB
PDF
No ratings yet
Computer Programming: Introduction To MATLAB
57 pages
Arrays, Matrices and Array Operations
PDF
No ratings yet
Arrays, Matrices and Array Operations
54 pages
Matlab Workshop
PDF
No ratings yet
Matlab Workshop
81 pages
Basic MATLAB Programming Course
PDF
No ratings yet
Basic MATLAB Programming Course
155 pages
Structural Engg
PDF
No ratings yet
Structural Engg
27 pages