MATLAB
MATLAB
Sintaxis básica
Ejemplo Descripción
x = pi Cree variables con el signo igual (=).
El lado izquierdo (x) es el nombre de la variable que contiene el valor del lado derecho
(pi).
y = sin(- Puede proporcionar entradas a una función utilizando paréntesis.
5)
Gestión de escritorio
Función Ejemplo Descripción
save save data.mat Guarde su espacio de trabajo actual en un archivo MAT.
Tipos de arreglos
Ejemplo Descripción
4 escalar
[3 5] vector fila
[1;3] vector columna
[3 4 5;6 7 8 matriz
]
Vectores uniformemente espaciados
Ejemplo Descripción
1:4 Cree un vector de 1 a 4, con un espaciado de 1, usando el operador de dos
puntos (:).
1:0.5:5 Cree un vector de 1 a 4 con un espaciado de 0.5.
Creación de matrices
Ejemplo Descripción
rand(2) Cree una matriz cuadrada con 2 filas y 2 columnas.
Indexación
Ejemplo Descripción
Operaciones de arreglo
Ejemplo Descripción
[1 1; 1 1]*[2 2;2 2] Realice una multiplicación matricial.
ans =
4 4
4 4
[1 1; 1 1].*[2 2;2 Realice una multiplicación por elementos.
2]
ans =
2 2
2 2
Múltiples salidas
Ejemplo Descripción
[xrow,xcol] = size(x Guarde el número de filas y columnas de x en dos variables diferentes.
)
Documentación
Ejemplo Descripción
doc rand Abra la página de documentación de la función randi.
Ejemplo Descripción
i
Representación gráfica
Ejemplo Descripción
plot(x,y,"ro-","LineWidth",5 Represente una línea roja (r) de guiones (--) con un
) marcador circular (o) y un ancho de línea grueso.
Utilización de tablas
Ejemplo Descripción
data.HeightYards Extraiga la variable HeightYards de
la tabla data.
data.HeightMeters = data.HeightYards*0.914 Derive una variable de tabla a partir de los
4 datos existentes.
Lógicos
Ejemplo Descripción
[5 10 15] > 1 Compare un vector con el valor 12.
2
Programación
Ejemplo Descripción
if x > 0.5 Si x es mayor que 0.5, establezca el valor de y en 3.
y = 3
else En caso contrario, establezca el valor de y en 4.
y = 4
end
title
xlabel
ylabel
legend
grid
Example
Formatted Text
To insert a line of text, click the Text button in the Text section of the Live Editor tab in the
MATLAB Toolstrip.
Comments
To create a comment, add % comment where you want to add more information.
load AuDeMx
% Converts from US$/gal to US$/L
gal2lit = 0.2642; % conversion factor
Germany = gal2lit*Germany;
Australia = gal2lit*Australia;
Mexico = gal2lit*Mexico;
Summary: Manually Entering Arrays
Create a Row Vector
Use square brackets and separate the values using a comma or a space.
Example
a = [10 15 20 25]
a =
10 15 20 25
Create a Column Vector
Example
b = [2;3;5;7]
b =
2
3
5
7
Transpose a Vector
'
.
Example
c = b'
c =
2 3 5 7
Create a Matrix
Use square brackets and enter values row-by-row. Separate values in a row using a comma or a
space, and use a semicolon to start a new row.
Example
A = [1 3 5;2 4 6]
A =
1 3 5
2 4 6
Introduction: Creating Evenly-Spaced Vectors
Suppose you want to create a vector containing every integer from 1 to 10. You'll need to type
every number from 1 through 10.
v = [1 2 3 4 5 6 7 8 9 10];
Now what if you want your vector to contain every integer from 1 to 25?
v = [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25];
Creating long vectors by manually entering every value can be tedious. In this lesson, you'll learn to
create vectors containing evenly-spaced elements using more compact syntax that uses the colon
operator (:) and the function linspace.
Colon Operator
The colon operator, :, is useful for when you know the desired spacing between elements of the
vector (and the start and end points).
x =
a:dx:
b
x = -4:3:8
x =
Creates a vector that starts at -4, ends at 8, and elements are
separated by 3. -4 -1 2
5 8
x = 1:4
x =
To create a vector with spacing 1, you can omit the spacing value in
the syntax. MATLAB will use a default spacing of 1. 1 2 3
4
x = 1:4:15
x =
The vector always contains the start point, but may or may not contain
the end point. 1 5 9
13
Linspace
In some cases, when creating an evenly-spaced vector, you may know the number of elements you
want the vector to contain, and not the spacing between the elements. In these cases, you can
use linspace.
When
Syntax Vector Created to use
x = a:dx:b When
eleme
nt
spacin
g is
known
x = When
linspace(a, numbe
b,n) r of
eleme
nts is
known
A nice feature of linspace is that it guarantees the resulting vector will contain both the start and
end point specified. Some examples:
x = linspace(1,7,5)
x =
Creates a vector that starts at 1, ends at 7, and
contains 5 elements. 1.0000 2.5000 4.0000
5.5000 7.0000
x = linspace(-pi,pi,4)
x =
Creates a vector that starts at -pi, ends at pi,
and contains 4 elements. -3.1416 -1.0472 1.0472
3.1416
Use the colon operator to separate the starting value, interval, and the ending value.
Example
a = 3:2:7
a =
3 5 7
When Interval is 1
Use the colon operator to separate the starting and the ending value.
Example
b = 3:7
b =
3 4 5 6 7
Given the Start Value, End Value, and Number of Elements
Use the function linspace when the number of elements in the vector are known.
Example
c = linspace(3.2,8.1,5)
c =
3.2 4.42 5.65 6.87 8.1
Summary: Concatenating Arrays
Horizontal Concatenation
Vertical Concatenation
Combined Concatenation
Create each row separating elements with a comma (,) or space ( ), then separate the rows with
a semicolon (;)
fun(m,n)
m-by-n
Calling syntax Output
fun(n)
n-by-n
x = rand(260,1);
So how do you access your data? How can you extract subsets of data for comparison? And how
can you modify specific elements?
Because MATLAB stores everything as an array – even scalars are 1-by-1 arrays – accessing
elements of an array is a core skill that you'll use every time you work in MATLAB.
In this chapter, you'll learn how to use indexing to extract subsets of arrays.
Introduction: Indexing into Vectors
If you know the smallest element of a vector has an index (location) 9, how can you extract that
value to use in calculations or store in a separate variable? In other words, how can you use the
location number to extract a value from a vector?
In this lesson, you will learn to find and modify a value in a vector given its index (location).
Step 1 - Create an Index
Example
I = 1:3
I =
1 2 3
Step 2 - Indexing
Example
s = v(I)
s =
15 20 25
Step 1 and Step 2
Example
s = v(1:3)
s =
15 20 25
Assign Multiple Elements
Example
v(1:3) = 10
v =
10 10 10 30 35
Multiple Values
Example
v(1:3) = [15 10 5]
v =
15 10 5 30 35
Summary: Matrix Indexing
Row, Column Indexing
Whether you're indexing into a matrix with scalar values or vector values, the format is always the
same.
Use the row number to index.
If multiple rows are to be extracted, create a vector containing the row numbers and use that as
the row index.
output = M(row,column)
Use the column number or a vector of column numbers to be extracted as the column index.
output = M(row,column)
This is row-comma-column indexing. Separate the row index and column index by a comma.
output = M(row,column)
Extract a single element
Summary: Performing Array Operations
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
sin Sine
cos Cosine
log Logarithm
mod Modulus
Many more
Scalar Expansion
Operators
+ Addition
Operators
- 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
Functio
n Description
Using min and max
Ignoring NaNs
avg = mean(v,'omitnan')
Function Behavior
var Variance
A = [8 2 4 ; 3 2 6 ; 7 5 3 ; 7 10 8]
A =
8 2 4
3 2 6
7 5 3
7 10 8
Amax = max(A)
Amax =
8 10 8
Astd = std(A)
Astd =
2.2174 3.7749
2.2174
Asum = sum(A)
Asum =
25 19 21
Many statistical functions accept an optional dimensional argument that specifies whether the
operation should be applied to columns independently (the default) or to rows.
>>
M
= mean(
A
,
dim
)
M Vector of average values along dimension dim.
Outputs
A Matrix
Inputs
Function Description
histogra Histogram
m
Additionally, you can interactively discover plot types by selecting variables in the Workspace
browser, and then browsing the available plot types in the Plots tab of the toolstrip.
Summary: Identifying Available Vector Plot Types
Function Description
histogra Histogram
m
array.
xticks
xticklabels
xtickangle
You can use the optional "line specification" input to the plot function to set the line and marker
style and color:
This modifies three of the many properties that govern the appearance of line plot objects.
As you create visualizations, you can further precisely control their appearance by specifying the
values of the properties of the objects that comprise your plots. In the above example, the red line
has been widened and the blue circular markers have been filled with a custom color
You can experiment with modifying other properties, such as the line width. Other than the
properties that can be changed with line specification input (marker, line style, and line color), the
most commonly modified properties for a line plot are:
Different graphical objects, including different plot types, have different sets of properties. Rather
than try to remember the vast number of property names for each of the various types of graphical
objects, you can access detailed documentation on MATLAB Graphics Objects Properties.
When you are finished, you can move on to the next section.
plot(x,y,linespec,Property1,Value1,Property2,Value2,Property3,Value3,...)
z
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
You can try to answer this question by comparing the numbers of wins and losses at home.
MATLAB provides operators for such comparisons. You can then extract a subset of the data, not
by providing the indices, but by using a certain criterion. This is referred to as logical indexing.
In this chapter, you will learn to
Summary: Logical Operations and Variables
Relational Operators
== Equal
~= Not equal
Example
v = [6 7 8 9];
w = [2 4 8 16];
NE = v ~= w
NE =
1 1 0 1
Logical Operators
& AND
| OR
~ NOT
Example
v = [6 7 8 9];
w = [2 4 8 16];
x = 5;
A = (v > x) & (w > x)
A =
0 0 1 1
Summary: Counting Elements
Purpose Function Output
What are the indices of the elements that are true? find double
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:
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
tw = EPL.HW + EPL.AW
tw =
You can use dot notation to extract 23
data for use in calculations or plotting. 20
19
19
draws = EPL{:,{'HD','AD'}}
If you want to extract multiple draws =
variables, you can do this using curly 6 6
braces. 4 7
2 7
5 4
writetable(tableName,'myFile.txt')
The file format is based on the file extension, such as .txt, .csv, or .xlsx.
writetable
Wins
____
23
20
3
teamInfo
teamInfo =
Team
Manager
________________
_________________
'Arsenal' 'Arsène
Wenger'
'Aston Villa' 'Eric
Black'
'Leicester City' 'Claudio
Ranieri'
[EPL games]
ans =
Team Points
Wins
________________ ______
You can concatenate tables that are the ____
same length but do not share a common 'Leicester City' 81
variable. 23
'Arsenal' 71
20
'Aston Villa' 17
3
EPL = join(EPL,teamInfo)
EPL =
Team Points
Manager
___________________ ______
___________________
The join function can combine tables with a
common variable. 'Leicester City' 81
'Claudio Ranieri'
'Arsenal' 71
'Arsène Wenger'
'Aston Villa' 17
'Eric Black'
Description: ''
UserData: []
DimensionNames: {'Row'
Display the table properties. 'Variable'}
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
Columns 1 through 4
You can access an individual {'Team'} {'HomeWins'}
property of Properties using dot {'HomeDraws'} {'HomeLosses'}
notation. Columns 5 through 8
{'HomeGF'} {'HomeGA'}
{'AwayWins'} {'AwayDraws'}
Columns 9 through 11
{'AwayLosses'} {'AwayGF'}
{'AwayGA'}
sortrows(teamInfo,'ManagerHireDate')
ans =
Manager
ManagerHireDate
_________________
Many functions operate on datetime _______________
arrays directly, such as sortrows. '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
ts = datetime([1903;1969],[12;7],
To create a vector, you can specify an [17;20])
array as input to the datetime function. ts =
17-Dec-1903
20-Jul-1969
ismissing(x)
ans =
The ismissing function identifies only 1×7 logical array
the NaN elements by default. 0 1 0 0 0 0
1
xNaN =
standardizeMissing(x,-999)
Use the standardizeMissing function to convert xNaN =
all missing values to NaN. 2 NaN 5 3
NaN 4 NaN
Ignores NaNs by default
(default flag Includes NaNs by default
is 'omitnan') (default flag is 'includenan')
max cov
min mean
median
std
var
double NaN
single
datetime NaT
duration NaN
calendarDuration
categorical <undefined>
Polynomial Fitting
Determine the coefficients
You can use the function polyfit to compute the coefficients of a least-squares polynomial fit to
the data.
>>
c
= polyfit(
x
,
y
,
n
)
c Vector of polynomial coefficients.
Outputs
Inputs
x = 0:5;
y = [2 1 4 4 3 2];
plot(x,y)
Suppose
that you
have two
vectors x a
nd y.
Fit a c = polyfit(x,y,3)
polynomial c =
of degree 3
to the x- -0.1296 0.6865 -0.1759 1.6746
y data.
Coefficients in the output vector are ordered from the highest to the lowest degree. So, the
polynomial which fits the x-y data can be expressed as:
Given the vector c containing the coefficients of the polynomial, you can evaluate the polynomial at
any value of x using the polyval function.
>>
yFit
= polyval(
c
,
xFit
)
yFi Value of the polynomial at the given points (yFit = p(xFit)).
t
Outputs
Inputs
A common
approach is
to create a
vector of
uniformly
spaced x va
lues.
at values
contained in
the
vector xFit.
Simple fitting
Fit polynomial to data. c = polyfit(x,y,n);
Programming Constructs
Course Example: Comparing Gasoline Prices
So far, the MATLAB scripts you have created have always executed the exact same
sequence of commands. To change the script's behavior, you manually edited the code
within it.
What if you want a user to be able to provide input? Or execute different sets of commands
based on some condition?
The matrix prices contains the average annual gasoline prices where the columns
represent the countries and the rows represent the years 1990 through 2008.
In this chapter, you will learn programming constructs that allow your programs to make
decisions or repeat a procedure multiple times.
User interaction
Decision branching
Loops
You can use these constructs to make your code more robust, more flexible, and more
maintainable.
otherwise
If none of the cases are a match, then the code, code_3, in otherwise is
code_3
executed. The otherwise block is optional.
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 is
code_e
executed.
code_1
If expression equals value_1, then code_1 is executed. Otherwise, the next
case is tested. There can be any number of cases. case value
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
You could imagine a scenario where the data contains n columns, and later one more
column is added. If you hard-coded n into your for loop, e.g. for idx = 1:n, then that
last column would not get processed in the for loop with the modified data.
You will learn about functions size, length, and numel and when to use each one.
[m,n] =
size(prices)
m =
19
Use size to find the dimensions of a matrix. n =
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 dimensions m =
returned by size is 1. 19
Use numel to find the total number of elements in an array of any N = numel(prices)
dimension. N =
190
One option is to find the best fit line between each set of countries.
c1 = polyfit(ctryPrices,prices(:,1),1)
c1 =
0.8395 -1.1204
c2 = polyfit(ctryPrices,prices(:,2),1)
c2 =
1.2980 -0.5513
c3 = polyfit(ctryPrices,prices(:,3),1)
c3 =
1.5914 -1.8551
...
cN = polyfit(ctryPrices,prices(:,end),1)
cN =
0.2598 0.7888
Rather than typing out similar commands over and over, you can use a for loop to execute a
block of code repeatedly.
While Loops
To use a for loop, you need to know in advance how many iterations are required. If you want to
execute a block of code repeatedly until a result is achieved, you can use a while-loop.
For the gasoline prices application, you may wish to ask the user for the name of a country, and if
it doesn't exist, ask for another name until a name in the list is provided. This can be done using a
while-loop.
while-Loops
A while-loop has the structure while condition
shown. statement 1
statement 2
The code statements 1, 2, 3, etc. statement 3
…
are executed while condition end
evaluates to true.
findPower.mlx
1. n = 0;
2. r = x;
3. while r > 1
4. r = x/(2^n);
5. n = n+1;
6. end
Workspace
53
x
0
n
53
r
1.
2.
3.
4.
5.
6.
1.
2.
3.
4.
5.
6.
1.
2.
3.
4.
5.
6.
1.
2.
3.
4.
5.
6.
1.
2.
3.
4.
5.
6.
Press Ctrl+C.
Click Stop in the
Toolstrip
For example, an
analysis of
electricity usage
data could
contain these
steps:
Import
data from
a file
Preproces
s the data
Fit a
polynomi
al to
selected
data
Use the
fit to
predict
usage at a
future
date
Plot the
data and
fitted
model
What's
the name
of the
data file?
What's
the degree
of the
polynomi
al to fit?
What's
the future
date to
predict
usage for?
What if you want to perform the analysis for a different file? Or a different degree
polynomial, or a different future prediction date? You'll need to manually modify their
values in the script and re-run it.
A better solution is to create a function that takes the filename, the degree of the
polynomial, and the future date as inputs.
In this chapter, you'll learn to create and call functions. You'll also learn how to manage
variables within functions and understand how MATLAB finds a variable or function.
You can write a script (as shown to the right) that sorts the vectors and then extracts the
first three elements of the sorted vectors.
Here, you are repeating the code to sort the vector and extract the three largest elements for
the vectors x and y. You can instead create a function that takes a vector as an input and
outputs another vector containing the top three elements.
The syntax for defining a function is similar to the syntax for calling any MATLAB function with the
keyword function at the beginning.
Note that functions defined at the bottom of the script file can only be called from within
the script file. You cannot call this function from the Command Window or other scripts.
In many situations, it is useful to create a function that is accessible from outside of the
script file. In this lesson, you will learn to create functions that can be called from the
Command Window, scripts, and other functions.
The file must have the same name as the function to create.
getTopN.mlx
1.
2.
3.
4.
1.
2.
3.
4.
1.
2.
3.
4.
getTopN.mlx
To run the function, you should call the function with the necessary input arguments from
the Command Window or from another function or a script.
getTopN.mlx
v = [12 5 -2 15 99 87 0 -9
1. function topN = getTopN(v,N) 8];
2. sortedv = top2 = getTopN(v,2)
sort(v,'descend'); top2 =
3. topN = sortedv(1:N); 99 87
4. end
Local functions:
Visible only within the file where they are
Functions that are defined within a
defined.
script.
Functions:
Functions that are defined in separate Visible to other script and function files.
files.
Introduction: Workspaces
MATLAB scripts share the base workspace, i.e., they can read or modify any variables in
the base workspace.
A function has its own workspace, separate from the base workspace.
Using functions creates fewer variables in the base workspace, which results in fewer
variable name conflicts. This lesson focuses on function workspaces.
Summary: Workspaces
A function maintains its own workspace to store variables created in the function body.
foo.mlx
a = 42;
1. function y = foo(x)
b = foo(a); 2. a = sin(x);
3. x = x + 1;
4. b = sin(x);
5. y = a*b;
6. end
Function Workspace
-0.9165
Base Workspace a
42 -0.8318
a b
0.7623 43
b x
0.7623
y
MATLAB Files
electricityAnalysis.mlx
polyPrediction.mlx
visualizePrediction.mlx
EPLAnalysis.mlx
elec_ind.csv
EPL.csv
EPL.mat
Current Folder
These files can access each other and can also be used from the Command Window when the
current directory is set to that particular folder.
Calling Precedence
Using functions reduces the possibility of variable name conflicts. However, you can still
have conflicts if a user-created function has the same name as a built-in MATLAB function
or if a variable has the same name as a function.
Suppose you use a variable named date to store the date of the first observation from the
electricity data.
elecData = readtable('elec_res.csv');
date = elecData.Dates(1)
date =
01-Jan-1990
Base Workspace
315x2
table
elecData
1x1
datetime
date
However, MATLAB has an in-built function also named date that returns a character vector
containing today's date.
date.m
Now, if you try to use date, will MATLAB refer to the variable in the Workspace or the function
named date?
nextDate = date + 1
or ?
date.m
date
Troubleshooting Code
When writing
programs
consisting of
several
commands, coding
errors or mistakes
are inevitable.
As a result,
MATLAB will
generate error
messages when
those programs
are run.
There are two types of errors that you will see when you program: syntax errors and run-time
errors.
In this lesson, you will learn to use tools that help identify the cause of syntax and run-time errors.
Introduction: Code Analyzer
When MATLAB encounters an error while running code, it displays an error message.
You can call the function and fix these errors one at a time. A better approach is to use the
MATLAB Code Analyzer, which identifies syntax errors in a script or function before you
execute code.
Icon Meaning
In this lesson, you will learn how to use the MATLAB debugger to investigate and resolve
errors such as this.
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.