Matlab Fundamental
Matlab Fundamental
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.
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.
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.
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.
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;
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')
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.
- 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.
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.
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.
- 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).
(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.
A = [ 1 1 1 ; 1 1 1 ]; C = [ 0 ; 0]; x = [ A C ]
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
(1/7) Introduction: If you wanted to create the following matrix, it would be tedious to enter all the
elements individually.
Example MATLAB contains many functions that help you to create commonly used matrices, such
as matrices of all ones.
A = ones(10,7)
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.
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)
fun(m,n)
m-by-n
fun(n)
n-by-n
(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,[])
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
(1/7) Introduction
- 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.
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)
- 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.
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])
- 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)
plot(Year90s,Price90s,'o')
hold on
plot(Year00s,Price00s,'o')
hold off
v=
15 10 5 30 35
- 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)
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])
In this chapter, you'll learn how to perform mathematical and statistical operations with
matrices and vectors.
5/11 Quiz
1. The difference between matrix addition (+) and array addition (.+) is:
Scalar Expansion
Arithmetic Operators
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.
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
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.
Element 1,1.
Element 1,2.
Element 2,1.
Element 2,2.
A squared matrix.
(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.
(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.
[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
avgValue = mean(inputVector,'omitnan')
gọi là omitNaN
(6/6) Summary
Common Statistical Functions
Function Description
Ignoring NaNs
When using statistical functions, you can ignore NaN values
avg = mean(v,'omitnan')
Many statistical functions accept an optional dimensional argument that specifies whether the
operation should be applied to columns independently (the default) or to rows.
xAvg=mean(x,1)
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)
TASK xD=diff(x)
Create a matrix named xD which contains the
difference between adjacent rows of x.
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)
xMin=min(x,[],2)
(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.
(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)