0% encontró este documento útil (0 votos)
139 vistas

MATLAB

El documento proporciona una introducción a MATLAB y resume varias funciones básicas. Explica cómo crear variables y funciones, gestionar el espacio de trabajo, diferentes tipos de arreglos como escalares, vectores y matrices, y operaciones con arreglos como indexación y multiplicación matricial. También cubre la representación gráfica, lógicos, programación básica con bucles y condicionales, y la documentación de funciones.

Cargado por

Erika Suarez
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como DOCX, PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
139 vistas

MATLAB

El documento proporciona una introducción a MATLAB y resume varias funciones básicas. Explica cómo crear variables y funciones, gestionar el espacio de trabajo, diferentes tipos de arreglos como escalares, vectores y matrices, y operaciones con arreglos como indexación y multiplicación matricial. También cubre la representación gráfica, lógicos, programación básica con bucles y condicionales, y la documentación de funciones.

Cargado por

Erika Suarez
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como DOCX, PDF, TXT o lee en línea desde Scribd
Está en la página 1/ 96

Resumen de MATLAB Onramp

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.

load load data.mat Cargue las variables de un archivo MAT en el espacio de trabajo.


clear clear Borre todas las variables del área de trabajo.
clc clc Borre todo el texto de la ventana de comandos.
format format long Cambie la forma en que se muestra una salida numérica.

 
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.

linspace(1,10,5 Cree un vector con 5 elementos. Los valores están espaciados uniformemente


) de 1 a 10.

 
Creación de matrices
Ejemplo Descripción
rand(2) Cree una matriz cuadrada con 2 filas y 2 columnas.

zeros(2,3 Cree una matriz rectangular con 2 filas y 3 columnas.


)

 
Indexación
Ejemplo Descripción

A(end,2) Acceda al elemento de la segunda columna de la última fila.

A(2,:) Acceda a toda la segunda fila.


A(1:3,:) Acceda a todas las columnas de las tres primeras filas.
A(2) = 1 Cambie el valor del segundo elemento de un arreglo a 11.
1

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

[xMax,idx] = max(x) Calcule el valor máximo de x y su correspondiente valor de índice.

 
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.

hold on Agregue la siguiente línea a la gráfica existente.


hold off Cree nuevos ejes para la siguiente línea representada.
title("My Title") Agregue una etiqueta a una gráfica.

 
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

v1(v1 > 6) Extraiga todos los elementos de v1 que sean mayores que 6.


x(x==999) = 1 Sustituya todos los valores de x que sean iguales a 999 por el valor 1.

 
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

for c = El contador de bucle (c) progresa a través de los


1:3 valores 1:3 (1, 2 y 3).
Ejemplo Descripción
disp(c) El cuerpo del bucle muestra cada uno de los valores de c.
end

Summary: Annotating Plots


Textual information can be added to plots using separate annotation functions. All of these functions
take text input.

title

Add title to plot

xlabel

Label the x-axis

ylabel

Label the y-axis

legend

Add legend to plot

Grid lines can be added or removed to plots.

grid

Display axes grid lines

Example

title('International Gasoline Prices')


xlabel('Year')
ylabel('Price (USD/L)')
legend('Germany','Australia','Mexico',...
'Location','northwest')
grid on
 

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.

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

Use square brackets and separate the values using a semi-colon.

Example

b = [2;3;5;7]

b =
2
3
5
7
Transpose a Vector

Use the transpose operator 

'
.

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

Syntax Vector Created

x =
a:dx:
b

Here are some examples:


x = 1:2:7
x =
Creates a vector that starts at 1, ends at 7, and elements are
separated by 2. 1 3 5
7

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

If the number of elements is omitted, linspace defaults to creating a vector with 100 elements.

Note that both the colon operator and linspace create row vectors.

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

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

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 (;)

Summary: Array Creation Functions


Several functions exist that allow you to create arrays.

      
 

Most of these functions support the calling syntaxes shown below.

Calling syntax Output

fun(m,n)

m-by-n
Calling syntax Output

fun(n)

n-by-n

Summary: Reshaping Arrays


The following column of information is reshaped into a matrix.

x = rand(260,1);

Specify the dimensions for the new array. y =


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

Accessing Data in Arrays


You can import your data into MATLAB as an array, or create arrays directly. And while many
operations work with entire arrays, you may want to find a particular element, or perform analysis on
subsets of your data.

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

Introduction: Accessing Multiple Elements


Suppose you want to extract the Australian gasoline prices corresponding to all the years in the
1990s. After creating the index of elements to be extracted, 1:10, you will have to use this index to
extract the actual values.
In this lesson, you will learn to extract and modify multiple elements of a vector.
Summary: Accessing Multiple Elements
Extract Multiple Elements

To extract elements from a vector:

 
Step 1 - Create an Index

Create a vector containing the index or locations of elements to be extracted.

Example

I = 1:3

I =
1 2 3
Step 2 - Indexing

Use the index inside the parentheses.

Example

s = v(I)

s =
15 20 25
Step 1 and Step 2

You can also combine steps 1 and 2.

Example

s = v(1:3)

s =
15 20 25
Assign Multiple Elements

Use multiple indexing with assignment to modify multiple elements at once.


Same Value

Assign one value to multiple elements.

Example

v(1:3) = 10

v =
10 10 10 30 35
Multiple Values

Assign different values to multiple elements.

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

Other Similar Functions

sin Sine

cos Cosine

log Logarithm

roun Rounding Operation


d

sqrt Square Root

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

Summary: Calculating Statistics of Vectors


Common Statistical Functions

Functio
n Description

min Returns the minimum element


Functio
n Description

max Returns the maximum element

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')

Summary: Statistical Operations on Matrices


Some common mathematical functions which calculate a value for each column in a matrix include:

Function Behavior

max Largest elements

min Smallest elements

mean Average or mean value

media Median value


Function Behavior

mode Most frequent values

std Standard deviation

var Variance

sum Sum of elements

prod Product of elements

      

A = [8 2 4 ; 3 2 6 ; 7 5 3 ; 7 10 8]
A =

8 2 4
3 2 6
7 5 3
7 10 8

Amax = max(A)
Amax =

8 10 8

Astd = std(A)
Astd =

2.2174 3.7749
2.2174

Asum = sum(A)
Asum =

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

>>
M
= mean(
A
,
dim
)
M Vector of average values along dimension dim.

Outputs

A Matrix

di Dimension across which the mean is taken.


m 1: the mean of each column
2: the mean of each row

Inputs

Introduction: Identifying Available Vector Plot Types


When exploring data sets, it's helpful to visualize the data in different ways. You might want to use
an area chart to visualize the difference between two series, or a scatter plot to visualize the
correlation.
MATLAB provides functions to create several standard chart types.
Additional Vector Plot Types
MATLAB has many specialized plotting commands to allow you to visualize and present your data
with the emphasis on the data features you find important.

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

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

scatter Scatter plot, with variable marker size and color


Function Description

bar Bar graph (vertical and horizontal)

stem Discrete sequence (signal) plot

stairs Stairstep graph

area Filled area plot

pie Pie chart

histogra Histogram
m

See the complete list of all available plots here.

Introduction: Annotations using Arrays of Text


How can you change x-axis tick labels to month names rather than numbers?
When visualizing textual data, you might need to create a variable containing several separate
words. In such cases, it is useful to store these character vectors distinctly instead of combining
them in a single vector. You can do this using a data type called a cell array.

Single 'Jan Apr Jul Oct'


Vector

'Jan 'Apr' 'Jul' 'Oct'


Cell Array
'

Summary: Annotations Using Arrays of Text


Cell arrays of text are useful for annotating visualizations. Use curly braces, {}, to create a cell

array.

xticks

Sets tick locations along the x-axis.

xticklabels

Labels the x-axis ticks.

xtickangle

Rotates the x-axis tick labels.


Introduction: Customizing Plot Properties
Customizing your visualizations can not only make them more aesthetically appealing but also more
informative and easier to interpret.

You can use the optional "line specification" input to the plot function to set the line and marker
style and color:

plot(x,y,'r*:') % red dotted line with asterisk markers

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:

 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)

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.

Summary: Customizing Plot Properties


Specifying Property Values

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

Common line properties to modify:

 'LineWidth' (width of the line and marker edges)


 'MarkerSize' (size of the marker symbols)
 'MarkerEdgeColor' (color of the edge of the marker symbols)
 'MarkerFaceColor' (color of the interior of the marker symbols)
 'Color' (color of the line, particularly when given as RGB values)
MATLAB Line Properties reference
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.

Introduction: Plotting Multiple Columns


Below you can see a plot of electricity revenue data. Each month is represented by a different
colored line and plotted over a span of several years.
Is it necessary to break the matrix into separate vectors to plot the data, or can the data remain in a
matrix for plotting?
Summary: Plotting Multiple Columns
You can use the plot function on a matrix to plot each column as a separate line in your plot.
Introduction: Visualizing Matrices
 
You can use line plots to visualize the electricity revenue data shown. But, there are so many
legend entries, it can be difficult to understand what's going on. Given the three-dimensional nature
of the revenue data, you could use a surface plot to more clearly represent the data.
Summary: Visualizing Matrices
You can use visualization functions to plot your three-dimensional data.

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

The surf function plots surf(z)


each point 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 coordinat
es, 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

Finding Data Based on Criteria


Sports teams generally have a better record when playing at their home ground. Was this true for
the teams of the Premier League, a professional men's soccer league in England and Wales, in the
2015-16 season?

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

 use logical and relational operators to test if a condition is true,


 count the number of times it is true, and
 extract data based on the result.

 
Summary: Logical Operations and Variables
Relational Operators
== Equal

> Greater than

< Less than

>= Greater than or equal

<= Less than or 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

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

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


x > 4
z =
y(idx
)
 

Summary: Storing Data in a Table


The readtable function creates a EPL = readtable('EPLresults.xlsx');
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',
The array2table function can {'Wins','Draws','Losses'})
convert a numeric array to a table. stats =
The VariableNames property can
be specified as a cell array of Wins Draws Losses
names to include as variable ____ _____ ______
names in the table.
20 11 7
12 14 12
23 12 3
19 9 10

Summary: Sorting Rows of Table Data


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

Use the EPL = sortrows(EPL,'HomeWins','descend');


optional 'descend' paramet
er to sort the list in
descending order.

You can also sort on multiple EPL = sortrows(EPL,


variables, in order, by {'HomeWins','AwayWins'},'descend');
specifying a cell array of
variable names.

You can also summary(EPL)


show summary statistics for
variables in a table.

Summary: 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

Inside parenthesis, specify the row EPL(2:4,[1 2 5])


numbers of the observations and column ans =
numbers of the table variables you would Team HW AW
like to select. ___________________ __ __
'Arsenal' 12 8
'Manchester City' 12 7
'Manchester United' 12 7
EPL(2:4,{'Team','HW','AW'})
You may also use the name of the variable ans =
for indexing. Team HW AW
___________________ __ __
If you want to reference more than one 'Arsenal' 12 8
variable, use a cell array containing the 'Manchester City' 12 7
variable names. 'Manchester United' 12 7

Summary: 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 extract 23
data for use in calculations or plotting. 20
19
19

You can also use dot notation to


create new variables in a table. EPL.TW = EPL.HW + EPL.AW
EPL =
Team HW HD
HL AW AD AL TW
___________________ __ __
__ __ __ __ __
'Leicester City' 12 6
1 11 6 2 23
'Arsenal' 12 4
3 8 7 4 20
'Manchester City' 12 2
5 7 7 5 19
'Manchester United' 12 5
2 7 4 8 19

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

Summary: Exporting Tables


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

writetable(tableName,'myFile.txt')

The file format is based on the file extension, such as .txt, .csv, or .xlsx.

writetable

Write a table to a file.

Summary: Combining Tables


Display the original tables. EPL
EPL =
Team Points
___________________ ______
'Leicester City' 81
'Arsenal' 71
'Aston Villa' 17
games
games =

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'

Introduction: Table Properties


Did you know that
a table stores more
than the variables
and observations
that you can see in
the Variable
Editor?

You can access


and modify
metadata such as
variable names,
units, description,
and more from the
table's Propertie
s.

Summary: Table Properties


EPL.Properties
ans =
Table Properties with properties:

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'}

Summary: Indexing into Cell Arrays

The varNames = teamInfo.Properties.VariableNames


variable varNames  'Team 'Payroll_M_ 'Manager 'ManagerHireDat
is a cell array that ' _' ' e'
contains character
arrays of different
lengths in each
cell.

Using parentheses varName(2)


to index produces 'Payroll_M__'
a cell array, not the
character array
inside the cell.

In order to extract varName{2}


the contents inside 'Payroll_M__'
the cell, you should
index using curly
braces, { }.

Using curly braces varName{2} = 'Payroll'


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

Summary: Working with Dates and Times


teamInfo
ans =
Manager
ManagerHireDate
_________________
Dates are often automatically detected _______________
and brought in as datetime arrays. 'Rafael Benítez' 3/11/2016
'Claudio Ranieri' 7/13/2015
'Ronald Koeman' 6/16/2014
'David Unsworth' 5/12/2016
'Slaven Bilić' 6/9/2015

sortrows(teamInfo,'ManagerHireDate')
ans =
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

You can create a datetime array using t = datetime(1977,12,13)


numeric inputs. The first input is year, t =
then month, then day. 13-Dec-1977

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

Summary: Representing Discrete Categories


x is a cell array. x = {'C','B','C','A','B','A','C'};
y = categorical(x);

You can convert x into a


categorical array, y, using
the categorical function.

You can use == to create a logical nnz(x == 'C')


array, and count elements ans =
using nnz. 3

You can view category statistics summary(y)


using the summary function. A B C
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

Summary: Working with Missing Data


Data contains missing values, in the form of both - x = [2 NaN 5 3 -999 4 NaN];
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

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


ans =
1×7 logical array
that ismissing identifies all the missing elements. 0 1 0 0 1 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

Data Type Meaning of "Missing"

double NaN
single

cell array of char Empty string ('')

datetime NaT

duration NaN
calendarDuration

categorical <undefined>

Summary: Moving Window Operations


movmin Moving minimum

movmax Moving maximum

movsum Moving sum

movmean Moving mean


movmedia Moving median
n

movstd Moving standard deviation

movvar Moving variance

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

Mean calculated with a moving window with kb points z = movmean(y,


backward and kf points forward from the current point. [kb kf])

Summary: 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.
Plot yyaxis left
multiple plot(...)
series yyaxis right
together. plot(...)
Plot plotmatrix(data)
variable
s
against
each
other.
Calculat corrcoef(data)
e linear ans =
correlati 1.0000 0.8243 0.1300 0.9519
on 0.8243 1.0000 0.1590 0.9268
coefficie 0.1300 0.1590 1.0000 0.2938
nts. 0.9519 0.9268 0.2938 1.0000

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

x Location of data points (independent variable


values).

y Data to fit polynomial to (y = p(x)).

n Degree of fitted polynomial.

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:

   p(x) = -0.1296 x3 + 0.6865 x2  - 0.1759 x + 1.6746

Evaluate the polynomial

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

c Vector of polynomial coefficients.

xFit Location of points (independent variable values) at


which to evaluate the polynomial.

Inputs

You can xFit = -1:0.01:6;


evaluate the
polynomial
at any
arbitrary
values of x.

A common
approach is
to create a
vector of
uniformly
spaced x va
lues.

Evaluate xFit = -1:0.01:6;


and plot the yFit = polyval(c,xFit);
fitted hold on
polynomial plot(xFit,yFit)
hold off

at values
contained in
the
vector xFit.

Summary: Polynomial Fitting


polyfit

Fits a polynomial to data.


polyval

Evaluates a polynomial at specified locations.

Simple fitting
Fit polynomial to data. c = polyfit(x,y,n);

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

Fitting with centering and scaling


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

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

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.

Summary: User Interaction


ctry = inputdlg('Enter a
country:');

You can use inputdlg to gather input from the


user.

You can use disp to show output on the command disp('Message')


window. Message
warning('Missing data')
You can use warning and error as well. Warning: Missing data
error('Missing data')
Missing data
msgbox('Analysis complete')

The msgbox, errordlg, and warndlg functions


can display messages to the user.

Introduction: Decision Branching


You can create a program that will respond to a user's input, taking different actions based on that
input.
This is known as decision branching and allows you to control which commands get executed in
your program based on a condition. Here we will discuss two methods for decision branching: the
if-elseif-else construction and the switch-case construction.

The switch-case Construction


If there is a finite set of discrete possible values for a variable (e.g., a set of menu options or the
number of dimensions of an array), you can use the switch-case construction in place of an if-
elseif-else construction.
The expression contains an expression that evaluates to a value. switch
expression
case
value_1
code_1
If expression equals value_1, then code_1 is executed. Otherwise, the
case
next case is tested. There can be any number of cases. value_2
code_2

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.

Always end the expression with the keyword end end


Here is an example.

Define x in the workspace. x = 2;


switch x
case 1
disp('x is 1')
case 2
Run the switch-case code. disp('x is 2')
otherwise
disp('x is neither 1
nor 2')
end
The output shows that the statements in the case where
x==2 are executed. x is 2
Summary: 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 is
code_e
executed.

Always end the expression with the keyword end end

Evaluate expression to return a value. switch


expression
case value
1

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

Always end the expression with the keyword end end

ntroduction: Determining Size


When writing MATLAB code, it is important to be able to determine the dimensions of
arrays programmatically, rather than by looking at their size in the workspace.

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.

Summary: Determining Size


s = size(prices)
s =
19 10

[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

Introduction: For Loops


Suppose you want to analyze the relationship between the gasoline prices of a selected country
and the gasoline prices of all the countries in the list. How could you do this?

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.

Summary: For Loops


for index =
The index is defined as a vector. Note the use of the colon first:increment:last
syntax to define the values that the index will take. code
end

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.

Suppose you want to find


n
such that
x/2n
is less than 1. You can write a while-loop and divide x by
2n
in the body of the loop as long as the result is greater than 1.

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.

Initialize the value of n to 0. Also, create a variable r to store the intermediate


computations, and initialize r to be
x/20
, i.e.,
x
.
Infinite Loops
A common problem when writing code with while-loops is the creation of infinite loops.
This usually happens if the variables involved in condition are not updated in the
statements block. However, even if they are updated, it is possible that condition will
never evaluate as false.
n = 0;
r = x;
Notice that the variable n is not incremented in the body of the while r > 1
loop.     r =
x/(2^n);    
end
If this happens, you can interrupt execution and stop the while-loop.

 Press Ctrl+C.
 Click Stop in the
Toolstrip

Summary: While Loops


The condition is a variable or expression that evaluates to true or false. While while
condition is true, code executes. Once condition becomes false, the loop condition
code
ceases execution. end

Increasing Automation with Functions


Course Example: Electricity Consumption in Different
Sectors
In a script, you're
usually
implementing a
complete data
analysis
workflow.

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

The first few


lines of your
script define
some important
parameters for
the analysis:

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

Creating and Calling Functions


Suppose you need to extract the three largest elements from the vectors x and y.

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.

Step 1 - Define a function at the bottom of the script file.

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.

Summary: Creating and Calling Functions


Define a function Call a function

Introduction: Function Files


Functions that are defined inside a MATLAB script file (called local functions) can be accessed only
by the script in which they live.
You can run the script which calls the local function defined in the script.

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.

Creating Function Files


To create a function that is accessible from the Command Window and other script and
function files:

Step 1 - Create a new code file.

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.

Calling Function Files


If you try to use the 'Run' button to execute the code in a function file, you will get an error
because the input arguments will not be assigned any value.

getTopN.mlx

1. function topN = getTopN(v,N)


2.     sortedv = sort(v,'descend');
Error using getTopN (line 2)
3.     topN = sortedv(1:N);
Not enough input arguments.
4. end

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

Summary: Function Files


Function Type Function Visibility

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.

script1.mlx script2.mlx script3.mlx


Suppose you have three scripts.

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

Introduction: MATLAB Path and Calling


Precedence
A large application can have a number of MATLAB script, function, and data files. How
can you organize these files?

Option 1 - Store files in a single folder

Current Folder >> predictedusage =


polyPrediction('elec_ind.csv',...
datetime(07,01,2019),3);
predictedusage =
2.7583e+06

  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.

Adding Folders to MATLAB Path


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.
MATLAB can access the data and code files in the folders on the search path irrespective
of the current 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.

>> v = [12 5 -2 15 99 87 0 -9 8];


>> t2 = getTopN(v,2);
Suppose you call the function getTopN from the Command Window.

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.

Using the MATLAB Code Analyzer


Let’s look at the function polyPrediction. Does the code have any errors?

Summary: Code Analyzer


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

Icon Meaning

There is a potential for unexpected results or poor code performance.

There are syntax errors that must be addressed.

Introduction: Debugging Run-Time Errors


Removing syntax errors from your code does not mean that the code is error free.
pUsage =
Consider the function call which produces the run- predictUsage(data,pDate,3);
time error shown. Error using polyval (line 67)
Inputs must be floats, namely
It can sometimes be difficult to understand why single or double.
the error occurred without knowing the broader Error in predictUsage (line 10)
context such as the variable values. usagePred =
polyval(c,endDuration);

In this lesson, you will learn how to use the MATLAB debugger to investigate and resolve
errors such as this.

Summary: Debugging Run-Time Errors


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.

También podría gustarte