You are on page 1of 42

Scripts and the Base Workspace

Scripts can operate on the variables that are present in the base workspace before the script is run.
Similarly, the variables that are generated after the script is run are stored in the base workspace.

3.3 Code selection

3.3.1 Introduction: Code Sections

The overall structure of most scripts can naturally be divided into different sections. This is especially
nice for larger files where you may just want to focus on one area, such as adjusting a plot.

Sections allow you to modify and reevaluate the code in just that section to see the impact.

3.3.2 Adding and Running Code Sections

Adding Code Sections

You can create separate code sections by adding a section break.

On the Live Editor tab in the Toolstrip, in the Section section, click Section Break.

You can also add a section break by using the keyboard shortcut Ctrl+Shift+Enter.
Running Code Sections

You can run the code sections through the Section section of the Live Editor tab in the Toolstrip.

Run Section: Run code in the current section.


Run and Advance: Run code in the current section, then move
to the next section.
Run to End: Run code in the current section and all code after
it.
When you run a section using the “Run Section” button, all the sections following the selected
section are also executed.

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

You can use the controls on the Live Editor tab of the toolstrip to create, navigate to, and run
different sections.

3.4 Comments and Text:

3.4.1 Introduction: Comments and Text


Readability of your code file is
important if you want to quickly
scan your code to recall what it
does, or share it with a colleague
who isn't familiar with it.
As the number of lines of code in
a script file increases, it becomes
harder to interpret the code.

Adding text descriptions that are


not executed allows you to
explain the functionality of your
code.

3.4.2 Comments and Formatting

Formatted Text

You can add a line of text to a live script by clicking the Text button in the Text section of the Live
Editor tab in the MATLAB Toolstrip. You can then 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. Comments let
you annotate a continuous block of code without inserting lines of text. Comments can appear on
lines by themselves, or they can be appended to the end of a line.
load AuDeMx
% Converts from US$/gal to US$/L
gal2lit = 0.2642; % conversion factor
Germany = gal2lit*Germany;
Australia = gal2lit*Australia;
Mexico = gal2lit*Mexico;

3.5 Sharing Live Scripts:

Introduction: Sharing Live Scripts


You may want
to share your
code and
results with
your
colleagues. You
can share your
live scripts
directly with
other MATLAB
users, or you
can publish a
static
document that
includes your
code,
formatting,
links, and plots.

Exporting Live Script Files

You can export your live script and results


using the Save button in the Live Editor tab.
Available formats include PDF, HTML, and
LaTeX.
The saved file will closely resemble the live
script when viewed in the Live Editor with
output inline.
3.6 Project - Using Scripts:

3.5 Sharing Live Scripts:

Introduction: Sharing Live Scripts

You may want to


share your code and
results with your
colleagues. You can
share your live
scripts directly with
other MATLAB
users, or you can
publish a static
document that
includes your code,
formatting, links,
and plots.

Exporting Live Script Files

You can export your live script and results using the Save button in the Live Editor tab.
Available formats include PDF, HTML, and LaTeX.
Plain code files (.m)

To share your code with users of previous MATLAB versions, you can save a live script as a plain
code file (.m). Users will be able to open and run your file, and any formatting will be converted to
comments with markup.
3.6 Project - Using Scripts:
(1/2) height
The file height.mat contains three variables:
 ageMos: vector of ages values in months from 24 to 240
 htMcm: vector of average male height values in cm that correspond to the ages in ageMos
 htFcm: vector of average female height values in cm

The script loads the variables and converts the data to height in feet, htM and htF.
TASK
Convert ageMos to age in years, age.

Then plot the male, htM, and female, htF, heights in feet against age in years, age.

Add a legend to the top left corner of your plot describing both lines.
Forgot to use break section
Load data
load height load height
cmPerFt = 30.48; cmPerFt = 30.48;
htM = htMcm/cmPerFt; % htM = htMcm/cmPerFt; % convert to feet
convert to feet htF = htFcm/cmPerFt;
htF = htFcm/cmPerFt; age = ageMos/12; % convert to years
% convert ageMos to years
age=ageMos/12; Plot heights
plot(age,htM); plot(age,htM)
hold on hold on
plot(age, htF); plot(age,htF)
hold off hold off
% add a legend topleft legend('Male','Female','Location','northwes
legend('male height','female t')
height','location','southwest xlabel('Age (yrs)')
') ylabel('Height (ft)')
title('Height by Age')

(2/2) Boston Temperatures


Two variables are in the file boston.mat:
 highs contains the daily high temperatures in °F in Boston, Massachusetts for 2005
 lows contains the daily low temperatures in °F in Boston, Massachusetts for 2005
TASK
Load boston.mat. Plot highs in red and lows in blue on one plot. Add a legend describing each
line.

Load and plot data


% TODO - load data
load boston
% TODO - plot highs and lows
plot(highs,'r')
hold on
plot(lows,'b')
hold off
xlabel('day')
ylabel('Temperature (\\circF)')
title('Boston Temperatures in 2005')
legend('Highs','Lows','Location','south')

4.1 Course Example - Arrays of Data: (1/5) Arrays of Data

Creating and Manipulating Arrays


In this chapter, you'll learn how to create, combine, and manipulate arrays.
In MATLAB, every variable is stored in
memory as an array – a variable which holds
one or more values.

Most of the time, you'll import your data


into MATLAB as an array. But how do you
create arrays directly in MATLAB, without
importing a file?

(2/5) Vectors, Matrices, and Arrays

Let's start by looking at some commomly used terms used to describe different numeric variables.
You will find these terms used in the rest of this course as well as in MATLAB documentation.
Depending on its dimensions, a variable is called as a scalar, a vector, or a matrix.

In general, a variable that contains multiple values is called an array. Scalars, vectors, and matrices
are therefore (numeric) arrays.

For example: Which of the following is the most appropriate term for a 3-by-1 (3 rows, 1 column)
array? It is a column vector.

Press cltr shift enter to execute or run the editor.

Press alt shift enter to break section

4.2 Manually Entering Arrays:

(1/5) Creating Vectors

- When you separate numbers by spaces (or commas), MATLAB combines the numbers into
a row vector, which is an array with one row and multiple columns (1-by-n). When you
separate the values by semicolons, ;, MATLAB creates a column vector (n-by-1) varName =
[1;3].
- You can also perform calculations directly within the square brackets. varName = [5 1 4*2]
varName = 5 1 8
- You can use the transpose operator ' to transform a row vector into a column (or vice
versa).
Use the MATLAB operator ' to
transpose a vector.
v = [3 6 9];
vt = v'
vt =
3
6
9
(2/5) Creating Matrices
- You can combine spaces and semicolons to create matrices. Enter a row of numbers, then
use a semicolon to separate rows. All rows must be the same length.
x = [ x11 x12 ;x21 x22 ; x31 x32 ]
x=
x11 x12
x21 x22
x31 x32
- You can also use the transpose operator ' on a matrix to transform the rows into columns
and vice versa.
AT = A'
CT = C'
As with vectors, the operator ' can calculate the complex conjugate transpose. If you want
to transpose a matrix of complex numbers without calculating the complex conjugate, use
the operator .'. When you are finished, you may move on to the next section.

4.3 Creating Evenly-Spaced Vectors:

(1/8) Introduction 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.

(2/8) 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).
(3/8) 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.

A nice feature of linspace is that it guarantees the resulting vector will contain both the start and
end point specified. Some examples:

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.

(4/8) Use Colon Operator and Linspace

- Create a row vector named x that starts at 5, ends at 15, and whose elements are separated
by 1. x= [5:1:15] vs x = 5:15
- Create a row vector named x that starts at 5, ends at 15, and contains 13 evenly-spaced
elements. x=[5:(15-5)/13:15] is wrong vs x = linspace(5,15,13)
- Create a variable named x that contains the row vector shown below.
3 5 7 9 11
x=3:2:11
- Create a row vector named x that contains every number (integer) from 1 to 50 (1, 2, 3, ... ,
50).

4.4 Concatenating Arrays:

(1/10) Introduction
At times, you may have data in MATLAB in
different vectors or matrices. You can combine
this data into one matrix, making it faster to
perform analysis all at once.

Example 1: What is the value of x after the following code is executed?

A = [ 1 1 1 ; 1 1 1 ]; C = [ 0 ; 0]; x = [ A C ]

Example 2: What is the value of x after the following code is executed? A = [ 1 1 1 ; 1 1 1 ];

B = [ 0 0 0 ]; x = [ A ; B ]

- You can concatenate two matrices horizontally (side-by-side) if they are the same height
(have an equal number of rows). Use square brackets around the matrices and separate
them with a space.

x = [x11 ; x21];
y = [y11 y12 ; y21 y22];
z = [x y]
x11 y11 y12
x21 y21 y22
Create a 3-by-5 matrix named BC concatenating B and C where B is on the left and C is on
the right.
- You can concatenate two matrices vertically (stacked on top of one another) using ; if they
are the same width (have an equal number of columns).

Use square brackets around the matrices and separate them with a ;.
x = [x11 x12; x21 x22];
y = [y11 y12];
z = [x;y]
x11 x12
x21 x22
y11 y12
- Add a row containing 10, 11, and 12, in order, to the bottom of C. Name the resulting matrix
CR.
- Add a column containing 10, 11, and 12, in order, to the right of C. Name the resulting matrix
CC.

NO SHORTCUT

(9/10) Creating and Concatenating Arrays

4.5 Array Creation Functions:

(1/7) Introduction: If you wanted to create the following matrix, it would be tedious to enter all the
elements individually.

For this reason, MATLAB has a large


number of matrix creation functions that
will create commonly used arrays.

Example MATLAB contains many functions that help you to create commonly used matrices, such
as matrices of all ones.

Note that the first input to ones is the number


of rows, and the second input is the number of
columns.

A = ones(10,7)

Example Try using the eye function to create an identity matrix


E=eye(5,5)

Example M = magic(n) returns an n-by-n matrix constructed from the integers 1 through n2 with
equal row and column sums. The order n must be a scalar greater than or equal to 3.

(5/7) Creating Arrays of Random Numbers

The rand function creates a matrix of uniformly distributed random numbers. Random numbers can
be useful for creating simulations.

- Example: Create a 100-by-1 vector of uniformly distributed random numbers with the name
xU. Answer xU = rand(100, 1)
- Create a 100-by-1 vector of normally distributed random numbers with the name xN.
xN=randn(100,1)
- The randi function creates a matrix of uniformly distributed random integers. Provide the
maximum value as the first input, followed by the size of the array you want to create.
v = randi(maxVal,m,n).
Create a 100-by-1 vector of uniformly distributed random integers with a maximum value
of 10. Name the vector xI.
xI=randi(10,100,1)
- Histograms are a type of bar plot for numeric data that group the data into bins. After you
create a Histogram object, you can modify aspects of the histogram by changing its property
values. This is particularly useful for quickly modifying the properties of the bins or changing
the display.
histogram(X)
histogram(X,nbins)
histogram(X,edges)
histogram('BinEdges',edges,'BinCounts',counts)
histogram(C)
histogram(C,Categories)
histogram('Categories',Categories,'BinCounts',counts)
- Example create any histogram
A = magic(4)
B = ones(1,4)
C = rand(5,2)

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

fun(n)
n-by-n

4.6 Reshaping Arrays:

(1/9) Introduction

If you have electricity revenue data stored in a matrix, where each column has a year's worth of
data, you could plot each year's revenue individually.

What if you wanted to view the revenue as one line from start to finish? One way to do this is to
reshape the data from a matrix into a vector before plotting it.

- Example 1 A matrix named A is stored in the workspace. Create a matrix named B that
contains the data from A in eight rows and three columns.
B=reshape(A,8,3)
- For convenience, you can leave one of the dimensions blank, using [], when calling reshape
and that dimension will be calculated automatically. B = reshape(A,[],q)
Create a vector named C with all the data from A in one column. C=reshape(A,[],1)
- Did you notice that it's not necessary to specify the order in which the elements of A are
extracted? This is because MATLAB stores data in a column-major format.
M=[123;456]
M=
1 2 3
4 5 6
The matrix M is stored in memory as 1, 4, 2, 5, 3, 6. And, thus, the reshaped array is
populated in the same order along each column. reshape(M,3,2)
ans =
1 5
4 3
2 6
To extract elements row-wise, use the transpose operator, ', to transpose the matrix before
reshaping.
Chú ý điểm khác nhau giữa row-wise and column-wise
Create a vector named D with all the data in A in one row. Extract the data row-wise rather
than column-wise.
D = reshape(A',1,[])

In which order is the data in A stored?


A =
5 1
1 1
7 6

8/9 Dùng hàm mean để tính ra trung bình từ ma trận cột


The matrix revenue contains monthly electricity revenue data for the years 1990-2015. Each
column contains the monthly revenue for a given year (January through December).
Calculate the average monthly electricity revenue over all time, and name the result avgRev.
avgRev=mean(reshape(revenue,[],1))

Dùng hàm plot để


plot(revenue,'-') plot(reshape(revenue,[],1))

Remember there are two equivalent ways you can make a column vector from a matrix:
using reshape, and indexing with a colon.
reshape(revenue,[],1)
revenue(:)

9/9 Summary
Summary: Reshaping Arrays

4.7 Creating a matrix


5. Accessing Data in Arrays

1. Extract subsets of arrays, and modify elements in an array.


2. Course Example - Accessing Data in Arrays
3. Indexing into Vectors
4. Accessing Multiple Elements
5. Accessing Data in Matrices
6. Project - Accessing Data in Arrays

5.1 Course Example - 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.

5.2 Indexing into Vectors:

(1/7) Introduction

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).
(2/7) Accessing and Modifying Vector Values

- The location of each element in a vector is referred to as an index. In MATLAB, the index
of the first element in a vector is 1. You can access an element by providing the index within
the parenthesis after the variable name. The following command extracts the fourth
element of the vector x and stores it in the variable z.

Do not edit. This code defines the vectors x and y.


x = [19 0.86 1.517 3.685 2.3 10]
y = [20.00 1.60 3.637 8.538 3.123 8.9]
r = x(3)
- The colon operator can refer to a range of values. The following syntax extracts the first,
second, and third elements of x. z = x(1:3)
r3=x(2:4)
- Assign value
You can combine indexing with the assignment
operator to modify the value of a vector
element.
The following command assigns the value of
the variable z to the fourth element of the
vector x.
x(4) = z

(3/7) Index Using Variables and Keywords

Instead of using a number as an index directly,Define a variable called idx containing a value
you can use a variable that contains a number between 1 and 6. Use this variable as in index
as an index. For example, the following set of into the variable x. Store the result in p.
commands accesses the second element of x. idx=(1:6);
a = 2; p=x(idx)
y = x(a) idx=rand[1:6];
p=x(idx)
A variable that contains a number as an index Use idx to index into the variable y. Store the
can be used with any vector. result in p2.
a = 2; p2=y(idx)
z1 = x(a);
z2 = y(a);
You can use the MATLAB keyword end as an
index to reference the last element. For
example, the following command accesses the
last element of the vector x.
last = x(end);
You can perform arithmetic operations with
the keyword end to indicate the index. Try the
following commands and observe the results.
Which element is being accessed?
y(end-1)
y(end/2)

The vector y has 6 values. What happens if you


use the index end/2 with a vector containing 5
values?
z = rand(1,5)
z(end/2)
When you are finished practicing, please move
on to the next section.

(6/7) Indexing Gasoline Price Vectors


The first element of the vector Australia is NaN. Change the first element such that it has the same
value of the second element.
The first element of the vector Australia is NaN. Australia(1)=Australia(2)
Change the first element such that it has the
same value of the second element.

- Fff
The min and max functions can be used with
two outputs. The second output is the index
(location) of the maximum or minimum value.

Use the min function to find the minimum


Australian gasoline price and the index of the v = [31;12;8;29;36];
minimum value. Store the result in variables [m,idx] = min(v)
named minAus and idx.
m =
8
[minAus,idx]=min(Australia) idx =
3b

Use the variable idx as an index into the vector


Year to find the year corresponding to the
minimum Australian gasoline price. Store the
result in minAusYear.
minAusYear=Year(idx)

5.3 Accessing Multiple Elements:


- Introduction: Accessing Multiple Elements
In this lesson, you will learn to extract and modify multiple elements of a vector.

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.

- (3/8) Index with Vectors


1. To extract multiple elements from a vector, the first step is to create a vector of indices.

idx=x[2 4] -> sai

idx=x([2 4]) -> sai

idx = [2 4] -> đúng

2. You can use a vector containing element numbers as an index to extract elements from
another vector.
I = [1 3 4]; result = v(I); result contains the first, third and fourth elements of v.
- Use the variable idx as an index to extract the second and fourth elements of x. Store the
result in x24. x24= x(idx)
- Now extract the 4th, 7th, and 9th elements from x without creating a separate variable to
store the index. Store the result in x479.
x479 = x([4 7 9])
- Recall that the keyword end can be used as an index for the last element in a vector.
result = v(end)
You can use end in an index vector to access multiple elements.
last2 = v([end-1 end])
last2 contains the last 2 elements of v.
Extract the last three elements from x, in order, without creating a separate variable to
store the index. Use the keyword end in your command. Store the result in xLast3.
xLast3 = x([end-2:end])

- Instead of listing the last three elements of x individually, you can use a colon with the
keyword end to extract a range of elements. The command :
result = v(end-2:end) is equivalent to result = v([end-2 end-1 end])

Extract every element of x except the first and the last. Extract the elements in order
without creating a separate variable to store the index. Use the keyword end in your
command. Store the result in xIn.
xIn= x([2:end-1])

- Chú ý sự khác biệt giữa colon operator vs ([])


The colon operator is useful for extracting patterns of elements. For example, you can
extract every other element of x.
y = x(1:2:end)
y contains the odd-indexed elements (1st, 3rd, 5th, ...) of x. Try extracting the even-indexed
elements of x.
How would you extract the first 10 elements of x in reverse order? Remember you can use
the colon operator with the increment -1 to create a vector of decreasing values.
When you are finished practicing, please move on to the next section.

(4/8) Modify Multiple Elements


- You can change multiple elements of a vector at once by combining indexing with
assignment.
v = [1 3 6 9 2 5];
v(3:5) = 4
v=
1 3 4 4 4 5
The 3rd, 4th, and 5th elements of v are assigned the value 4.

- You can change multiple elements to different values by assigning a vector of values.
v = [1 3 6 9 2 5]; w = 21:23;
v(3:5) = w
v=
1 3 21 22 23 5
When performing multiple assignments in this way, the number of elements indexed on the left
of the equals sign must match the number of elements in the expression on the right.
Assign the values 10, 11, and 12 to the last 3 elements of x.
x([end-2:end]) =[10:13] -> sai nha VS x(4:6) = 10:12 -> đúng VS x([end-2: end]) = 10:12 -> đúng
- You can create new elements in a vector by assigning values to indices that does't exist.
For example, in the following example, v initially has only 4 elements. After the assignment,
the value 20 is assigned to the sixth element and the unassigned elements are given the
default value of 0.
v = [1 3 6 9];
v(6) = 20
v = 1 3 6 9 0 20
VD x(9:12)=100:103
- The colon operator is also useful for modifying patterns of elements. Try changing every
other element of x to 5. How would you create the following vector?
102030405
Try using the colon operator to assign the nonzero elements. When you are finished
practicing, please move on to the next section.
z([1 3 5 7 9])=1:5

(6/8) Quiz
What is the value of x after the code
shown is executed?
A = [3 1 2 12 4]
x = A(4:7)

(7/8) Plot Gasoline Prices by Decade

Plot Year90s on the x-axis and


Price90s on the y-axis. Then add a
plot of Price00s vs. Year00s. Use a
circle marker 'o' for both plots.
Remember to use hold off when
you are finished adding to your
plot.

plot(Year90s,Price90s,'o')
hold on
plot(Year00s,Price00s,'o')
hold off

8/8 Summary: Accessing Multiple Elements


1. Extract Multiple Elements
To extract elements from a vector: vector v
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

5.4 Accessing Data in Matrices:


(2/12) Row,Column Indexing
- You can extract values from an array using row, column indexing.
x = usage(rowNum,colNum)
Ví dụ: Try creating a variable v that contains the value in the 6th row and 3rd column of the
variable usage. v =usage(6,3)
- You can use the keyword end as either a row or column index to reference the last element.
The following code gets the element in the last row and last column of usage.
x = usage(end,end)
x=
92392875
Now try using the end keyword to obtain the value in the last row and 3rd column of the
variable usage. Assign this value to a variable named w. w=usage(end,3)

- You can use arithmetic with the keyword end. For example:
x = usage(end-1,end-2)
x=
72725759
Create a scalar variable p that contains the value in the second to last row and 3rd column
of usage.p = usage(end-1,3)

(3/12) Quiz
What is the value of x after the
code shown is executed?
A = [3 1 7; 5 4 2; 8 9 6 ];
x = A(2,3)
What is the value of x after the code shown
is executed?
A = [3 1 7; 5 4 2; 8 9 6];
x = A(end,1)
What is the value of x after the code
shown is executed?
A = [3 1 7; 5 4 2; 8 9 6];
x = A(end-1,2)

(7/12) Extract a single line


Task
TASK
A matrix named M is stored in the
workspace.
Create a variable named x which contains
the value of the element stored in the
highlighted location in the matrix M.

Create a variable named y which contains x=M(4,2)


the value of the element stored in the
highlighted location in the matrix M.
Use the end keyword to create a variable z2=M(end-1,end-1)
named z which contains the value of the
element stored in the highlighted location
in the matrix M.

(8/12) Matrix Indexing with Vectors


To extract an entire row or column from an y1993=usage(:,4)
array, you can use :.
x = usage(:,colNum);
The above code extracts a column from
usage.
What if you wanted to extract multiple Try creating a matrix evenYears that
rows or columns? You can index using a contains all the rows in columns 1, 3, and 5
vector containing those index values. of usage.

For example, both lines of the following evenYears=usage(:,[1 3 5])


code will extract the first three rows of
usage.
firstThree = usage(1:3,:);
firstThree = usage([1 2 3],:);

Try creating a matrix summer that contains summer =usage([6:8],:)


rows 6 through 8 of usage.
Try creating a matrix evenSummer that evenSummer =usage(6:8, [1 3 5]);
contains the elements in rows 6 through 8
from columns 1, 3, and 5 of usage.
Create a matrix mid1993 that contains the mid1993=usage([2:end-1],4)
elements from the second row through the
second-to-last row from column 4 in usage.

9/12 Quiz
(Select all that apply) Which of the
following commands will extract the fifth
column of a 40-by-5 matrix M?

10/12
TASK
A matrix named M is stored in the
workspace.
every5usage = usage(:,1:5:end);
Create a variable named x which contains every5price = price(:,1:5:end);
the value of the elements stored in the
highlighted location in the matrix M.
Create a matrix named every5 with every5=[every5usage;every5price]
every5usage on top of every5price.

12/12
Use the row number to index. output = M(row,column)
If multiple rows are to be extracted, create output = M(row,column)
a vector containing the row numbers and output = M(row,column)
use that as the row index.
Use the column number or a vector of
column numbers to be extracted as the
column index
This is row-comma-column indexing.
Separate the row index and column index
by a comma.
M Extract multiple elements output = M(2,[3 4])

Extract multiple contiguous elements output = M(2,2:4)


Extract complete rows or columns output = M(2,:)

5.5 Project - Accessing Data in Arrays

The file HWdata.mat contains the plot(HW(:,1),HW(:,2),'o')


height and weight data for 18 people
in a single matrix, HW. The first
column of HW has the heights in cm in
increasing order. Each individual's
corresponding weight in kg is the 2nd
column of HW.

Create a plot of height on the x-axis


and weight on the y-axis, using circle
markers ('o').

The first column of HW has the heights plot(HW(1:9,1),HW(1:9,2),'o')


in cm in increasing order. hold on
TASK plot(HW(10:end,1),HW(10:end,2),'o')
Split the 18 individuals into two hold off
halves, by height. Create a plot of
weight vs. height where the shorter
half and taller half are plotted in
different colors. Use circular markers
('o').

6.Performing operation math

6.1 Course example – electricity consumption


The file electricity.mat contains data representing electricity usage in the United States
from 1990 to 2015. To make it easier to analyze monthly or annual trends, the data is
organized so that the 12 rows represent 12 months and the 26 columns represent the years.

But how do you perform that analysis?


In MATLAB, you can perform mathematical operations (like addition and multiplication) and
statistical operations (like finding the mean) on arrays with a single command.

In this chapter, you'll learn how to perform mathematical and statistical operations with
matrices and vectors.

6.2 Performing Operations on Arrays:


(1/11) Basic Array Arithmetic & Functions
When performing arithmetic between a array
and a scalar, each element in the array is Create a matrix named x3 which
operated on by the scalar. subtracts each element of x from 3.
x3 = 3 -x

TASK: Create a matrix named x2 which halves


each value in x. x2 = x/2
Array addition and subtraction work element- Z=x +y
wise; the operation is applied to each of the
corresponding elements.
Create a variable named a which contains the a = (x+y)/2
average values of corresponding elements of
x and y. In other words, sum x and y element-
wise and divide the result by 2.
Most mathematical functions in MATLAB are Use the round function to round all the
vectorized and can operate on each element elements in a. Store the result in ar
of an entire array with one command
ar=round(a)

(2/11) Electricity price


Convert price from ¢/kWh to $/MWh. You price=price*1e3/100
can multiply price by 1e3/100 to make this
conversion.
Use the randn function to create a 12-by- noise=randn(12,26)
26 matrix named noise. Then create a nPrice=noise + price
matrix named nPrice that contains the
sum of noise and price.
Use the round function to round all the rPrice=round(nPrice,2)
elements in nPrice to 2 digits after the
decimal point. Store the result in rPrice

(3/11) Element-wise vs. Matrix Operations


(4/11) Element-wise Arithmetic

By default, multiplication, division, and Find the element-wise product of x and y


exponentiation operators are interpreted and name the result p.
as matrix operations in MATLAB. What p=x.*y
matrix operations are will be covered later.
In this lesson, you will learn about element-Divide each element in x by y and name the
wise operations, which operate element- result q.
by-element. q=x./y
Raise each element in x to the power of 3
If you want to perform an element-wise and name the result x3.
operation, prefix the operator with a dot, . x3=x.^3
Raise each element in x to the power of
each element in y and name the result xy.
xy=x.^y

5/11 Quiz
1. The difference between matrix addition (+) and array addition (.+) is:

(7/11) Calculating Revenue


Multiply price and usage in an element-wise revenue = price.*usage
manner. Name the result revenue.
Convert revenue to billions of dollars (divide by revBillion = round(revenue/1e9,3)
1e9). Then use round to round to three decimal
places. Name the result revBillion.
Calculate the ratio of the prices from 2015 (the priceInfl=price(:,end)./price(:,1)
last column of price) over the prices from 1990
(the first column of price).
Name the result priceInfl.
The geometric mean of two numbers can be Calculate the geometric mean of the prices
found by multiplying them together and taking from 1990 (the first column of price) and 2015
the square root of the result. (the last column of price). Name the result
gMean = sqrt(a*b); GMprice
GMprice=sqrt(price(:,1).*price(:,end))

(8/11) Implicit Expansion


(9/11) Operating on Compatibly-Sized Arrays
Array operations can also be performed on TASK
operands of different compatible sizes. Two What happens if you add vectors x and y?
arrays have compatible sizes if the size of each Assign the result to M.
dimension is either the same or one. M = x+y

You can use element-wise multiplication to M2=x.*M


multiply a vector and a matrix so that the vector
expands along one of the matrix dimensions.

(10/11) Adjusting Prices for Inflation


The workspace contains a vector dollar2015 of TASK
conversion factors for the years 1990 to 2015. Create a matrix named price2015 that contains
Each element of dollar2015 will convert the the 2015 dollar values for all the values in the
value of one dollar in a given year to the value matrix price.
of one dollar in the year 2015. price2015=price.*dollar2015
For example, the first element (corresponding
to the year 1990) will convert 1990 dollars to
2015 dollars.
Recall that each column of the matrix price
contains monthly electricity price data for a
given year.
Using the prices in 2015 dollar values, calculate priceR = price2015(:,end)./price2015(:,1)
the ratio of the 2015 prices (the last column of
price2015) over the 1990 prices (the first
column of price2015).
Name the result priceR.
(11/11) Summary
Mathematical Functions

Scalar Expansion

Arithmetic Operators

6.3 Matrix Multiplication:


(1/8) Introduction
When multiplying two matrices, * is not the same as .*.
Matrix Multiplication with * Element-wise Multiplication with .*

If you try to calculate a product with the multiplication operator, *, you see an error message.
This is because MATLAB is trying to perform matrix multiplication.

Multiplication, division, and exponentiation operators are interpreted in a mathematical matrix


sense. You will learn about matrix multiplication in this lesson.
(2/8) Matrix Multiplication

Matrix Dimensions
Matrix multiplication requires that the inner dimensions of the two matrices agree. The resultant
matrix from multiplication has the outer dimensions of the two matrices.

Matrix Multiplication

Here is an example of matrix multiplication. Note that matrix order is important.

Matrix multiplication requires that inner dimensions agree. In this case, the number of columns in
the first matrix, three, is equal to the number of rows in the second matrix, three.

Element 1,1: the elements of the first row of the first matrix are multiplied with the corresponding
elements in the first column of the second matrix and the resulting products are summed together.

Element 1,2: the elements of the first row of the first matrix are multiplied with the corresponding
elements in the second column of the second matrix and the resulting products are summed
together.

Element 1,3: the elements of the first row of the first matrix are multiplied with the corresponding
elements in the third column of the second matrix and the resulting products are summed together.

Element 1,4: the elements of the first row of the first matrix are multiplied with the corresponding
elements in the fourth column of the second matrix and the resulting products are summed
together.
Element 2,1: the elements of the second row of the first matrix are multiplied with the
corresponding elements in the first column of the second matrix and the resulting products are
summed together.

Element 2,2: the elements of the second row of the first matrix are multiplied with the
corresponding elements in the second column of the second matrix and the resulting products are
summed together.

Element 2,3: the elements of the second row of the first matrix are multiplied with the
corresponding elements in the third column of the second matrix and the resulting products are
summed together.

Element 2,4: the elements of the second row of the first matrix are multiplied with the
corresponding elements in the fourth column of the second matrix and the resulting products are
summed together.

The resultant matrix has a size equal to the outer dimensions. The number of rows in the first matrix,
two, by the number of columns in the second matrix, four.
Matrix Exponentiation

Taking the power of a matrix requires the matrix to be square in order to ensure agreement of the
inner dimensions.
Taking the power of a matrix requires a square matrix.

Taking the square of a matrix is equivalent to multiplying the matrix by itself.

Element 1,1.

Element 1,2.

Element 2,1.

Element 2,2.

A squared matrix.

(3/8) Matrix Operations

R=M1*M2 Multiply M1 and M2, name the result R.

Multiply M3 and M1, name the result B. B=M3*M1


Take each element of M4 to the third power. PE=M4.^3
Name the result PE.
Take the matrix M4 to the third power. Name the PM=M4^3
result PM.
Matrix multiplication is not commutative (A*B ≠
B*A). To solve a system of equations such as
x*A = B, you can use / to solve for x. This is a
preferable solution to using the inv function
because MATLAB uses sophisticated
algorithms to find the best solution with the
slash operator.
x = B/A

Likewise, to solve the system A*x = B, you can


use \.
x = A\B

Previously, you calculated B = M3*M1. Try to


solve the system for M1 and then M3.
M1Sol = M3\B
M3Sol = B/M1

When you are finished practicing, please move


on to the next section.

(4/8)
What is the size of z after the code shown is
executed?
x = [1 2 3; 4 5 6];
y = [1 1; 2 2; 3 3];
z = x*y;
Which of the following operations are valid?
A matrix must be square (in other words, have
the same number of rows and columns) in
order to take the power of it. There are two
square matrices in the solutions.

(T/F) The following equations for z1 and z2 are


equivalent.
x = [1 2 3 ; 2 3 4 ; 3 4 5];
y = [9 10 3 ; 10 7 6 ; 2 1 10];
z1 = x*y;
z2 = y*x;

(7/8) In this activity, you will calculate the weighted average of electricity prices from 1990 to 2015,
weighted by the value of 1USD relative to 2015.

Create a weighting vector named w that w = dollar2015/sum(dollar2015)


divides each element in the vector dollar2015
by the sum of elements in dollar2015.
Calculate the average with inflation, a, by a = price*w
multiplying w and price in the order that makes
sense.

(8/8) Summary: Matrix Multiplication


Matrix Multiplication
Matrix multiplication requires that the inner
dimensions agree. The resultant matrix has the
outer dimensions.

Matrix “Division” Expression Interpretation

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

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

6.4 Calculating Statistics of Vectors:


(1/6) Introduction
Introduction: Calculating Statistics of Vectors : MATLAB contains many functions that
you can use to calculate statistics of vectors. Some of the most common functions
include:

(2/6) Basic Statistics – Task


Use the function max to find the maximum m=max(x)
value contained in the vector x. Save the
result in a variable named m.
The min and max functions can be used v = [31;12;8;29;36];
[m,idx] = min(v)
with two outputs. The second output is
the index (location) of the maximum or m =
minimum value. 8
idx =
3
Use the max function to find the index
of the maximum value in the vector x.
Store the result in a variable named idx.
You may store the maximum value in a
variable of your choice.

[m,idx] = max(x)
Create a variable named r which contains r = mean(x)
the average value of x.
Create a variable named s which contains You can use the sort function to sort
the values of x in sorted ascending order. the values of a vector. By default, the
s=sort(x) values are sorted in ascending order.

The sort function can also sort values in To find the five largest values, you can
descending order. sort x in descending order, then extract
the first five elements of the sorted
vector.
xSorted = sort(x,'descend')
xSorted(1:5)

(3/6) Quiz

What is the size of x after the code shown is executed?


d = [1 2 3 4];
x = sort(d)
(5/6) Average Gasoline Prices
Find the average gasoline price in Australia. avgAus = mean(Australia)
Store in a variable named avgAus.
Notice that value of the variable avgAus is NaN. TASK
This is because the vector Australia contains a Find the average gasoline price in Australia
NaN value and any arithmetic with NaN results ignoring the NaN values. Store in a variable
in NaN. named avgAusN.

You can ignore the NaN values by providing


'omitnan' as the second input.

avgValue = mean(inputVector,'omitnan')
gọi là omitNaN

(6/6) Summary
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')

6.5 Using Statistical Operations on Matrices:


(1/12) Introduction
Check reference
(2/12) Statistics on Arrays

Some common mathematical functions which


calculate a value for each column in a matrix
include:

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

(3/12) Descriptive Statistics


Generally, statistical analysis functions in Create a row vector named xAvg which
MATLAB work on each column of a matrix contains the average value of each column x.
independently.

xAvg=mean(x,1)

Create a row vector named xMax which xMax=max(x)


contains the maximum value of each column of
x.
Create a row vector named xSum. For each xSum = sum(x,1)
column in x, sum the elements in that column
together.

4/12
What is the size of x after the code shown is 1 by 5
executed? Chỗ này phải xem lại 1 by 5 là dòng hay cột..
A = rand(3,5); quên hoài
x = mean(A)

(5/12) Rolling Calculations


Some analysis functions work column-wise by
default, but return multiple values for each
column. For example, the diff function
calculates the difference between adjacent
elements in each column of the input matrix.

TASK xD=diff(x)
Create a matrix named xD which contains the
difference between adjacent rows of x.

The cumsum TASK


function returns a Create a row vector named xSum which contains the sum of each column
matrix the same of x.
size as the input, Then create a matrix named cSum which contains the cumulative sum of
with the each column of x.
cumulative sum xSum=sum(x)
over each column. cSum=cumsum(x)

(6/12) Statistics for Each Row

TASK
Many statistical functions accept an optional Create a column vector named xAvg which
dimensional argument that specifies whether contains the average for each row of x.
the operation should be applied to the columns
independently (the default) or to the rows.
xAvg = mean(x,2)
The following command calculates the mean of
each row of A.
mean(A,2)

Create a column vector named xMed which xMed=median(x,2)


contains the median for each row of x.
In the min, max, and diff functions, the third TASK
input is reserved for the dimension to operate Create a column vector named xMin which
along. To skip defining the second input value, contains the minimum for each row of x.
use an empty array, [].
minRowElement = min(M,[],2); xMin=min(x,[],1)

xMin=min(x,[],2)

Create a matrix named xD which contains the xD = diff(x,[],2)


difference between adjacent columns in x.

What does the min function do if you supply 2


as the second input argument?
xSm = min(x,2)

Try using 7 to see if you can tell what's


happening.
xSm = min(x,7)

When you are finished practicing, please move


on to the next section.

(7/12) Quiz
What is the size of x after the code shown is 3 by 1
executed?
A = rand(3,5);
x = mean(A,2)

Vì 2 là
What is the size of x after the code shown is 3 by 5
executed?
A = rand(3,5);
x = cumsum(A,2)
(9/12) Correlation
Some analysis functions work on the entire TASK
matrix at once. Create a matrix named xCC which contains the
correlation coefficients of the columns of x.
The corrcoef function determines how well the
columns are correlated to one another. It xCC = corrcoef(x)
returns a square, symmetric matrix. Since it's
looking at column correlation, the number of
rows and columns returned are equal to the
number of columns in the original matrix.

TASK xCR=corrcoef(x')
Create a matrix named xCR which contains the
correlation coefficients of the rows of x.

Note that the corrcoef function always finds


the correlation between the columns of a
matrix. To find the correlation between the
rows, transpose the matrix.

(10/12) Quiz
What is the size of x after the code shown is 5 by 5
executed?
A = rand(10,5);
x = cov(A)

(11/12) Electricity Usage


Each column of the matrix usage contains plot(yr,mean(usage,1))
the monthly electricity usage data for a
given year.
TASK
Calculate the average annual electricity
usage for each year (i.e., the average of each
column of usage). Plot this average annual
usage versus yr.
Add two lines to the plot, one with the hold on
maximum and another with the minimum plot(yr,max(usage))
values for usage in each year. plot(yr,min(usage))
hold off
Each row of the matrix usage contains the TASK
yearly electricity usage data for a given Calculate the average electricity usage across all
month. years for each month (i.e., the average of each row
of usage). Use the bar function to plot your results.
For example, the first row of usage contains monthly = mean(usage,2);
the January electricity usage for the years bar(mth,monthly)
1990 through 2015.

Year-over-year change is a way of TASK


comparing one year of data to the previous Find the median year-over-year change in revenue
year. for each month. Use the bar function to plot your
results.
You can calculate the year-over-year change
for each month by using the diff function to YoY = diff(revenue,[],2);
subtract the previous year's values from the medYoY = median(YoY,2);
current year's values. bar(mth,medYoY)

6.6 Project - Analysis with Arrays:


(1/2) Natick Hourly Temperature Data

The following variables are loaded from the TASK


file natickData.mat: Determine the month with the largest
tempData: a matrix with the average hourly standard deviation in tempData. Save the
Fahrenheit temperature in Natick, largest standard deviation value as maxSd
Massachusetts, home of MathWorks, where and the month number as monthSd.
each row represents the hour of the day and
each column represents the month tempSd = std(tempData);
m: a vector with the month number during [maxSd,iSd] = max(tempSd);
which the measurements were taken monthSd = m(iSd)
hr: a vector with the hour during which the
measurements were taken.

Determine the month with the largest tempRange = max(tempData) -


temperature range in tempData. Save the min(tempData);
largest range as maxR and the corresponding [maxR,iR] = max(tempRange)
month number as monthMaxR monthMaxR = m(iR)
Now determine the month with the smallest
temperature range in tempData. Save the tempRange = max(tempData) -
smallest range as minR and the min(tempData);
corresponding month number as monthMinR [minR,iR] = min(tempRange)
monthMinR = m(iR)
Complete!

You can find the hourly change in


temperature using the diff function.
tempRate = diff(tempData)
At what time of day does the temperature
increase the fastest? Decrease the fastest?
[tempInc,iInc] = max(tempRate,[],2)
[tempDec,iDec] = min(tempRate,[],2)

When you are finished practicing, move on to


the next section.

(2/2) International Gasoline Prices


TASK
The file gasprices.mat contains the following Load the variables in the file gasprices.mat.
variables:
pricesDPG: matrix of gasoline prices in U.S.
dollars per gallon where each column
represents a different country and each row
a different year
yr: vector of year values from 1990 to 2008
cx: matrix of conversion values where each
column represents a currency corresponding
to a country and each row represents the
conversion rate for a particular year
litPerGal: scalar number of liters in a gallon
litPerYear: vector containing the average
liter consumption of gasoline per individual
per year from 1990 to 2008
country: string array containing the names of
the countries

Create a matrix named pricesYPL which pricesYPL = pricesDPG.*cx(:,6)/litPerGal


contains the gasoline prices in pricesDPG
converted from USD/gallon to Yen/liter. VS

The sixth column of cx contains values of the


Yen per USD for each year. The scalar pricesYPL = pricesDPG'*litPerGal*cx
litPerGal contains the number of liters in a
gallon.
Create a vector named totCost which totCost = mean(pricesYPL .* litPerYear)
contains the average yearly amount spent
(in yen) over the 19 years for a person in
each country.

Use the litPerYear vector which contains the


average number of liters purchased by a
person for each year.
Complete!

Try finding the largest average total cost.


[maxTC,idx] = max(totCost)
Which country does it correspond to?
Display the variable country and find the
element in the location idx.

When finished, move on to the next section.

You might also like