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

MATLAB Fundamentals Quick Reference

This document provides an introduction to fundamental MATLAB concepts: 1. It describes how to create and run scripts, use code sections, add comments and export live script files in the MATLAB desktop. 2. It explains how to create row and column vectors, matrices, and evenly spaced vectors using built-in functions like linspace and colon operators. It also covers concatenating and reshaping arrays. 3. It discusses indexing and extracting elements from arrays, as well as changing elements in arrays.

Uploaded by

shiva
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
567 views

MATLAB Fundamentals Quick Reference

This document provides an introduction to fundamental MATLAB concepts: 1. It describes how to create and run scripts, use code sections, add comments and export live script files in the MATLAB desktop. 2. It explains how to create row and column vectors, matrices, and evenly spaced vectors using built-in functions like linspace and colon operators. It also covers concatenating and reshaping arrays. 3. It discusses indexing and extracting elements from arrays, as well as changing elements in arrays.

Uploaded by

shiva
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

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 Run

Code Sections

Code sections allow you to organize your code and run sections of code independently. On the Live Editor tab, in the
Section section, click Section Break to create a new code section, or press Ctrl+Alt+Enter.

Load data

Convert units

Plot data

Label graph

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

LIVE EDITOR

Section Break

Run and Advance

Run
Run to End
Section

SECTION

Comments and Text

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

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

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

load gCosts

% Converts from US$/gal to US$/L

gal2lit = 0.2642;   % conversion factor

Germany = gal2lit*Germany;

Australia = gal2lit*Australia;

Mexico = gal2lit*Mexico;

Exporting Live Script Files


You can export your live script and results using


the Save button in the Live Editor tab.
Save

Available formats include PDF, Word, HTML, and


LaTeX.
Save

Save As…

Export to PDF…

Export to Word…

HTML…

LaTeX…

Export Folder…

3. Creating and Manipulating Arrays


Summary: Creating and Manipulating Arrays

Manually Entering Arrays

Create a Row Vector

Use square brackets and separate the values


a = [10 15 20 25]

using a comma or a space.

a =

10 15 20 25

Create a Column Vector

Use square brackets and separate the values


b = [2;3;5;7]

using a semi-colon.

b =

Transpose a Vector

Use the transpose operator ' .


c = b'

c =

2 3 5 7
Create a Matrix

Use square brackets and enter values row-by-row.


A = [1 3 5;2 4 6]

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

Creating Evenly-Spaced Vectors

Given the Start Value, End Value, and Interval

Use the colon operator to separate the starting


a = 3:2:7

value, interval, and the ending value.

a =

3 5 7

When Interval is 1

Use the colon operator to separate the starting


b = 3:7

and the ending value.

b =

3 4 5 6 7

Given the Start Value, End Value, and Number of Elements

Use the function linspace when the number of


c = linspace(3.2,8.1,5)

elements in the vector are known.

c =

3.2 4.42 5.65 6.87 8.1

Concatenating Arrays

Horizontal Concatenation

Separate elements using a


comma (,) or space (  )

Vertical Concatenation
Separate elements
using a semicolon (;)

Combined Concatenation

Create each row separating elements with a


comma (,) or space (  ), then separate the rows
with a semicolon (;)

Array Creation Functions

Several functions exist that allow you to create arrays.

       
Most of these functions support the calling syntaxes shown below.

Calling Output
syntax

fun(m,n)
m-by-n

fun(n)
n-by-n

Reshaping Arrays

The following column of information is reshaped into a matrix.

x = rand(260,1);

y = reshape(x,5,52);
Specify the dimensions for the new array.

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

4. Accessing Data in Arrays


Summary: Accessing Data in Arrays

Indexing

1 2 3 4

1 2.3 1 1.5 1.1 2.6 0.9

2 1.5 2 1.5 2.4 1.7 1.4

3 1.3 3 2.5 1.6 1.9 0.7

4 0.9 4 2.4 1.1 1.8 2.5

5 1.3 5 1.9 2.8 0.6 0.6

v M

v(2)

Extract one element from a vector


1.5

v(end)

Extract the last element from a vector


1.3

v([1 end-2:end])

Extract multiple elements from a vector 2.3

1.3

0.9

1.3

When you are extracting elements of a matrix you need to provide two indices, the row and column numbers.

M(2,3)

Extract one element from a matrix


1.7

M(:,end)

0.9

Extract an entire column. Here, it is the last one. 1.4

0.7

2.5

0.6
M([1 end],2)

Extract multiple elements from a matrix.


1.1

2.8

Changing Elements in Arrays

v(2) = 0

2.3

Change one element from a vector 0

1.3

0.9

1.3

v(1:3) = 0

Change multiple element of a vector to the same value 0

0.9

1.3

v(1:3) = [3 5 7]

Change multiple element of a vector to different values 5

0.9

1.3

v(9) = 42

Assign a non-existent value 0.9

1.3

42
v(1:3) = []

0.9

Remove elements from a vector 1.3

42

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, i.e., the operation is performed on each element of the
array individually.

Mathematical Functions

Other Similar Functions

sin Sine

cos Cosine

log Logarithm

round Rounding Operation

sqrt Square Root

mod Modulus

Many more
Scalar Expansion

Operators

+ Addition

- Subtraction

* Multiplication

/ Division

^ Exponentiation

Arithmetic Operators

Operators

+ Addition

- Subtraction

.* Element-wise Multiplication

./ Element-wise Division

.^ Element-wise Exponentiation

Note that, for performing the arithmetic operations on two matrices, they should have identical dimensions.

Implicit Expansion

Operators

+ Addition

- Subtraction

.* Element-wise Multiplication

./ Element-wise Division

.^ Element-wise Exponentiation

Array operations can be performed on operands of different compatible sizes. Two arrays have compatible sizes if the size of each
dimension is either the same or one.

Calculating Statistics of Vectors

Common Statistical Functions

Function Description

min Returns the minimum element

max Returns the maximum element


Function Description

mean Returns the average of the elements

median Returns the median value of the elements

Using min and max

Ignoring NaNs

When using statistical functions, you can ignore NaN values

avg = mean(v,"omitnan")

Statistical Operations on Matrices


Some common mathematical functions which A = [8 2 4 ; 3 2 6 ; 7 5 3 ; 7 10 8]
calculate a value for each column in a matrix
A =

include:

8 2 4

Function Behavior 3 2 6

7 5 3

max Largest elements


7 10 8

min Smallest elements

mean Average or mean Amax = max(A)


value
Amax =

median Median value

8 10 8

mode Most frequent values

std Standard deviation Astd = std(A)


var Variance Astd =

sum Sum of elements


2.2174 3.7749 2.2174

prod Product of elements

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)

Outputs Inputs
M Vector of average values along A Matrix
dimension dim .
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.

Solving Systems of Linear Equations

Expression Interpretation

x = B/A Solves x*A = B (for x )

x = A\B Solves A*x = B (for x )

6. Visualizing Data in 2D and 3D


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

Customizing Plot Properties

Specifying Property Values

plot(x,y,linespec,Property1,Value1,Property2,Value2,Property3,Value3,...)

See the complete list of line specifications here: https://www.mathworks.com/help/matlab/ref/linespec.html.

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

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.

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

z =

0 0 0 0 0

z is a 5-by-5 matrix 0 0 -6 0 0

0 -3 1 3 0

0 0 8 1 0

0 0 0 0 0

surf(z)

The surf function plots z(j,k) over the point x= k and y= j

x = 11:15;

y = 21:25;

surf(x,y,z)

To specify x and y coordinates, you can pass them in as vectors.


Here,
The number of elements of x must match the number of
columns of z
The number of elements of y must match the number of rows
of z

Exporting a Figure

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

Gasoline Prices
Australia
7
Germany
Mexico

Prices (USD/gal)
6

1
1990 1995 2000 2005
Year

7. Conditional Data Selection


Summary: Conditional Data Selection

Logical Operations and Variables

Relational Operators

v = [6 7 8 9];

== Equal
w = [2 4 8 16];

> Greater than NE = v ~= w

NE =

< Less than


1 1 0 1
>= Greater than or equal

<= Less than or equal

~= Not equal

Logical Operators

v = [6 7 8 9];

& AND
w = [2 4 8 16];

| OR x = 5;

A = (v > x) & (w > x)

~ NOT
A =

0 0 1 1

Counting Elements

Purpose Function Output


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

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

8. Review Project I

9. Tables of Data
Summary: Tables of Data

Storing Data in a Table

EPL = readtable("EPLresults.xlsx","TextType","string");
The readtable function creates a
table in MATLAB from a data file.

teamWinsTable = table(team,wins)

teamWins =

Team Wins

The table function can create a ___________________ ____

table from workspace variables.


"Arsenal" 20

"Chelsea" 12

"Leicester City" 23

"Manchester United" 19

stats = array2table(wdl, ...

"VariableNames",["Wins" "Draws" "Losses"])

The array2table function can stats =

convert a numeric array to a table.


The VariableNames property can Wins Draws Losses

be specified as a string array of ____ _____ ______

names
to include as variable names
in the table. 20 11 7

12 14 12

23 12 3

19 9 10

Sorting Table Data

EPL = sortrows(EPL,"HomeWins");
The sortrows function sorts the data
in ascending order, by default.

EPL = sortrows(EPL,"HomeWins","descend");
Use the optional "descend"
parameter to sort the list in
descending order.

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


You can also sort on multiple
variables, in order, by specifying a
string array of variable names.

summary(EPL)
You can also show summary statistics
for variables in a table.
Extracting Portions of a Table

EPL

EPL =

Team HW HD HL AW AD AL

___________________ __ __ __ __ __ __

"Leicester City" 12 6 1 11 6 2

"Arsenal" 12 4 3 8 7 4

Display the original table.


"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

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

ans =

Team HW AW

Inside parenthesis, specify the


___________________ __ __

row numbers of the


"Arsenal" 12 8

observations and column


"Manchester City" 12 7

numbers of the table variables


"Manchester United" 12 7

you would like to select.

EPL(2:4,["Team" "HW" "AW"])

You may also use the name of ans =

the variable for indexing.


Team HW AW

___________________ __ __

If you want to reference more "Arsenal" 12 8

than one variable, use a


string "Manchester City" 12 7

array containing the variable "Manchester United" 12 7

names.

Extracting Data from a Table

EPL

EPL =

Team HW HD HL AW AD AL

___________________ __ __ __ __ __ __

Display the original table.


"Leicester City" 12 6 1 11 6 2

"Arsenal" 12 4 3 8 7 4

"Manchester City" 12 2 5 7 7 5

"Manchester United" 12 5 2 7 4 8

tw = EPL.HW + EPL.AW

tw =

You can use dot notation to


23

extract data for use in


20

calculations or plotting.
19

19

EPL.TW = EPL.HW + EPL.AW

EPL =

Team HW HD HL AW AD AL TW

You can also use dot


___________________ __ __ __ __ __ __ __

notation to create new


"Leicester City" 12 6 1 11 6 2 23

variables in a table.
"Arsenal" 12 4 3 8 7 4 20

"Manchester City" 12 2 5 7 7 5 19

"Manchester United" 12 5 2 7 4 8 19

draws = EPL{:,["HD" "AD"]}

draws =

If you want to extract


6 6

multiple variables, you can


4 7

do this using curly braces.


2 7

5 4

draws13 = EPL{[1 3],["HD" "AD"]}

Specify row indices to draws =

extract specific rows. 6 6

2 7

Exporting Tables

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

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

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

writetable Write a table to a file.

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]

r
este
Leic al
en
Ars ham ity
ten C
To hester ited
t
Ma nc
er Un
t
nches
Ma

teamInfo games

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.

uswntTop3 posTop3

top3 = join(uswntTop3,posTop3)
top3 =

Player Goals Position

___________________ ______ ___________________

The join function can combine


tables with a common variable.
"Alex Morgan" 6 "midfielder"

"Megan Rapinoe" 6 "forward"

"Rose Lavelle" 3 "forward"

Table Properties
EPL.Properties

ans =

Table Properties with properties:

Description: ''

UserData: []

DimensionNames: {'Row' 'Variable'}

Display the table properties.


VariableNames: {1×11 cell}

VariableDescriptions: {1×11 cell}

VariableUnits: {}

VariableContinuity: []

RowNames: {}

CustomProperties: No custom properties are set.

EPL.Properties.VariableNames

ans =

1×11 cell array

You can access an


Columns 1 through 4

individual property of
{'Team'} {'HomeWins'} {'HomeDraws'} {'HomeLosses'}

Properties using dot


Columns 5 through 8

notation.
{'HomeGF'} {'HomeGA'} {'AwayWins'} {'AwayDraws'}

Columns 9 through 11

{'AwayLosses'} {'AwayGF'} {'AwayGA'}

Indexing into Cell Arrays

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

varName(2)
Using parentheses to index
produces a cell array, not
the character array inside 'Payroll_M__'
the cell.
varName{2}
In order to extract the
contents inside the cell, you
should index using curly 'Payroll_M__'
braces, { } .

varName{2} = 'Payroll'

Using curly braces allows


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

11. Specialized Data Types


Summary: Specialized Data Types

Working with Dates and Times

teamInfo

ans =

Manager ManagerHireDate

_________________ _______________

Dates are often automatically detected and brought in "Rafael Benítez" 3/11/2016

as datetime arrays. "Claudio Ranieri" 7/13/2015

"Ronald Koeman" 6/16/2014

"David Unsworth" 5/12/2016

"Slaven Bilić" 6/9/2015

sortrows(teamInfo,"ManagerHireDate")

ans =

Manager ManagerHireDate

_________________ _______________

Many functions operate on datetime arrays directly, "Ronald Koeman" 6/16/2014

such as sortrows . "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)
You can create a datetime array using numeric
t =

inputs. The first input is year, then month, then day.


13-Dec-1977
ts = datetime([1903;1969],[12;7],[17;20])

To create a vector, you can specify an array as input ts =

to the datetime function. 17-Dec-1903

20-Jul-1969

Operating on Dates and Times

seasonStart = datetime(2015,8,8)
seasonStart =

08-Aug-2015

Create datetime variables to work with.


seasonEnd = datetime(2016,5,17)

seasonEnd =

17-May-2016

seasonLength = seasonEnd - seasonStart

seasonLength =

Use subtraction to produce a duration variable.


6792:00:00

seasonLength = days(seasonLength)
Functions such as years and days can help seasonLength =

make better sense of the output. 283

seconds(5)
They can also create durations from a numeric ans =

value. 5 seconds

seasonLength = between(seasonStart,seasonEnd)
Use the between function to produce a context- seasonLength =

dependent calendarDuration variable. 9mo 9d

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

with functions such as calmonths and


2mo

calyears .

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 is a string array. x =

"C" "B" "C" "A" "B" "A" "C"

y = categorical(x);
You can convert x into a categorical
array, y , using the categorical y =

function. C B C A B A C

nnz(x == "C")
You can use == to create a logical
array, and count elements using ans =

nnz . 3

summary(y)
You can view category statistics
A B C

using the summary function.


2 2 3

y = mergecats(y,["B" "C"],"D")
You can view combine categories
y =

using the mergecats function.


D D D A D A D

12. Preprocessing Data


Summary: Preprocessing Data

Normalizing Data

normalize Normalize data using a specified normalization method.

xNorm = normalize(x)
Normalize the columns of a matrix using
z-scores.

xNorm = normalize(x,"center","mean")
Center the mean of the columns in a
matrix on zero.

xNorm = normalize(x,"scale","first")
Scale the columns of a matrix by the first
element of each column.

xNorm = normalize(x,"range",[a b])


Stretch or compress the data in each
column of a matrix into a specified
interval.
Working with Missing Data

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


Data contains missing values, in the form
of both -999 and NaN .

ismissing(x)

ans =

The ismissing function identifies only


1×7 logical array

the NaN elements by default.


0 1 0 0 0 0 1

ismissing(x,[-999,NaN])
Specifying the set of missing values ans =

ensures that ismissing identifies all the 1×7 logical array

missing elements. 0 1 0 0 1 0 1

xNaN = standardizeMissing(x,-999)
Use the standardizeMissing function to xNaN =

convert all missing values to NaN . 2 NaN 5 3 NaN 4 NaN

cleanX = rmmissing(xNaN)

Use the rmmissing function to remove cleanX =

missing values. 2 5 3 4

Ignores NaN s by default


Includes NaN s by default

(default flag is "omitnan" ) (default flag is "includenan" )

max
cov

min mean

median

std

var
Data Type Meaning of "Missing"

double
NaN
single

string array Empty string ( <missing> )

datetime NaT

duration
NaN
calendarDuration

categorical <undefined>

Interpolating Missing Data

fillmissing Fills missing values of an array or table.

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

z = fillmissing(y,"method","SamplePoints",x)
Interpolation with given observation
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.

"pchip" The cubic Hermite interpolating polynomial method forces the interpolant to maintain the same
monotonicity as the data. This prevents oscillation between data points.

13. Common Data Analysis Techniques


Summary: Common Data Analysis Techniques
Moving Window Operations

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

LIVE EDITOR

Task

The Smooth Data task uses the smoothdata function.

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

z = smoothdata(y,"movmean",[kb kf])
Mean calculated with a moving window
with kb points backward and kf points
forward from the current point.

z = smoothdata(y,"movmedian",k)
Median calculated with a centered moving
k-point window.

z = smoothdata(y,"movmedian",k,"SamplePoints",x)
Median calculated with a centered moving
k-point 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 corrcoef to calculate pairwise correlations.
yyaxis left

plot(...)

yyaxis right

plot(...)

Plot multiple series together.

plotmatrix(data)

Plot variables against each other.

corrcoef(data)

ans =

1.0000 0.8243 0.1300 0.9519

Calculate linear correlation coefficients.


0.8243 1.0000 0.1590 0.9268

0.1300 0.1590 1.0000 0.2938

0.9519 0.9268 0.2938 1.0000

Polynomial Fitting

polyfit Fits a polynomial to data.

polyval Evaluates a polynomial at specified locations.

Simple fitting

c = polyfit(x,y,n);
Fit polynomial to data.
yfit = polyval(c,xfit);
Evaluate fitted polynomial.

Fitting with centering and scaling

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

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

14. Programming Constructs


Summary: Programming Constructs

User Interaction

You can add a live control to get input from the user.

disp("Message")
You can use disp to show output on the command window.
Message

warning("Missing data")

Warning: Missing data

You can use warning and error as well.


error("Missing data")

Missing data
msgbox("Analysis complete")

The msgbox , errordlg , and warndlg functions can display


messages to the user.

Decision Branching

if condition_1

The condition_1 is evaluated as true or false .

code_1

If condition_1 is true , then the code_1 code block is executed.

elseif condition_2

code_2

Otherwise, the next case is tested. There can be any number of


cases.
elseif condition_3

code_3

else

If none of the cases are a match, then the code, code_e , in else
code_e

is executed.

end
Always end the expression with the keyword end

switch expression
Evaluate expression to return a value.

case value 1

If expression equals value_1 , then code_1 is executed. code_1

Otherwise, the next case is tested. There can be any number of


cases. case value 2

code_2

otherwise

If none of the cases are a match, then the code, code_3 , in


otherwise is executed. The otherwise block is optional.
code_3

end
Always end the expression with the keyword end
Determining Size

s = size(prices)
s =

19 10

[m,n] = size(prices)

m =

19

n =

Use size to find the dimensions of a matrix. 10

m = size(prices,1)

m =

19

n = size(prices,2)

n =

10

m = length(Year)
Use length when working with vectors where one of the m =

dimensions returned by size is 1 . 19

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

dimension.
190

For Loops
for index = first:increment:last

The index is defined as a vector. Note the use of the colon code

syntax to define the values that the index will take. end

While Loops

while condition

The condition is a variable or expression that evaluates to true or


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

Creating and Calling Functions

Define a function Call a function

Function Files

Function Type Function Visibility

Local functions:

Visible only within the file where they are defined.


Functions that are defined within a script.      

Functions:

Visible to other script and function files.


Functions that are defined in separate files.

Workspaces

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

foo.mlx
1. function y = foo(x)
a = 42;
2.     a = sin(x);
b = foo(a);
3.     x = x + 1;
4.     b = sin(x);
5.     y = a*b;
6. end

Base Workspace Function Workspace

  
a   42   a   -0.9165

  b   0.7623   b   -0.8318

  x   43

  y   0.7623

MATLAB Path and Calling Precedence

In MATLAB, there are rules for interpreting any named item. These rules are referred to as the function
precedence order.
Most of the common reference conflicts can be resolved using the following order:
1. Variables
2. Functions defined in the current script
3. Files in the current folder
4. Files on MATLAB search path

A more comprehensive list can be found here.

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

To add folders to the search path:


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

16. Troubleshooting Code


Summary: Troubleshooting Code

Code Analyzer

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

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.

Red indicator lines in the Code Analyzer. identify specific syntax errors. You can mouse over one to
see a
description of
that issue. The first indicator line describes the mistake
you saw in the error message: the closing quotation mark is
missing.

Clicking an indicator
line
puts your cursor where the error was found so you can fix it. Notice that the
broken portion of
the
code is red and underlined.

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.

Section Break: Add a section break to create


a code section.

This is the current section.

Run and Advance: Run code in the current


section, then move to the next section.

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.

17. Review Project II

18. Conclusion

You might also like