程序代写代做 AI C html graph Lab Session on Matlab

Lab Session on Matlab
2020/4/29

Overview
• Matrix, array operations and matrix operations
• Basic operations for plotting
• Basic operations in Table
• Exercise: Matlab programming for Homework 1 and 2

Matrix
• MatLab —- matrix laboratory
• A matrix is actually a two-dimensional array.
• The difference — operations, or used in different ways.
• A matrix is a two-dimensional array often used for linear algebra. • Matrix operations (will be introduced later in this class).
• Linear algebra is NOT a topic taught in this course.
• Want to learn linear algebra?
• Get a book or read online articles
• e.g. http://www.sosmath.com/matrix/matrix.html

Special matrices
Zero matrix: A matrix all of whose entries are zero 0 0 0 0
0 0 0 0 0 0 0 0
zeros()

Identity matrix: A square matrix which has ‘1’ s on the diagonal and zeros
everywhere else.
1 0 0 0 1 0
eye()
0 0 1 

Array operations
𝐴=12 B=56 34 78
44 44
5 12 21 32
A./B= 1/5 2/6 = 3/7 4/8
A.\B= 5/1 6/2 = 7/3 8/4
No .+ or .- operator!
A.+B
Error: unexpected MATLAB operator.
68 10 12
34 56
5 10 15 20
B – A= A.*B=
A+B= B – 2=
A*5=A.*5= 0.2 0.3333
0.4286 0.5000
53 2.333 2

Addition of two matrices
Matrix operations
If A and B are two matrices of the same size, then the sum of the matrices is a matrix C=A+B whose elements are the sums of the corresponding elements of A and B.
1 2 4 −1 3 10 0 5 14
A=−3 0 7 B=−3 1 0 C=A+B=−6 1 7
9 1 5 1 0 6 10 1 11 
• Addition of matrices is same as addition of arrays.
• MATLAB does not differentiate array addition and matrix
addition.
• Operator + for addition of arrays/matrices • No .+ operator

Matrix Subtraction
Matrix operations
If A and B are two matrices of the same size, then the difference of the matrices is a matrix C=A-B whose elements are the differences of the corresponding elements of A and B.
1 2 4 −1 3 10 2 −1 −6
A=−3 0 7 B=−3 1 0C=A-B=0 −1 7
9 1 5 1 0 6 8 1 −1 
• MATLAB does not differentiate array subtraction and matrix subtraction.
• Operator – for both array subtraction and matrix subtraction • No .- operator

Multiplication by a scalar
Matrix operations
If A is a matrix and c is a scalar, then the product cA is a matrix whose elements are obtained by multiplying each of the
elements of A by c
A=−3 0 7c=3
1 2 4 9 1 5

3 6 12
cA=−9 0 21
27 3 15 
• Same as multiplying an array and a scalar.
• Operator .* and operator * produce same result.

Scalar (dot) product of two vectors
Matrix operations
If a and b are two vectors of the same size
>> a=[1 2 3]; b=[4 5 6]; >> dot(a,b)
ans =
32
a1 b1 a = a ; b = b 
2 2 a  b
3 3
The scalar (dot) product of a and b is a scalar obtained by adding the products of corresponding entries of the two vectors
dot(a,b) =

Matrix multiplication
Matrix operations
For a product to be defined, the number of columns of A must be equal to the number of rows of B.
A B=AB m x r inside r x n m x n

Matrix multiplication
Matrix operations
If A is a mxr matrix and B is a rxn matrix, then the product C=AB is a mxn matrix whose entries are obtained as follows. The entry corresponding to row ‘i’ and column ‘j’ of C is the dot product of the vectors formed by the row ‘i’ of A and column ‘j’ of B
124 3 A =−3 0 7 B = 1
3×3   3×2   915 0
 −3 5
C =AB=10 −9 3×2 
−7 28 
−1 −3 1

Matrix Multiplication: Another example
2158 −9 0• =−45
 −2 10 −5 60

3 x 2 2 x 1 3x 1
dot(a,b) =ቊ𝑎 ∗ 𝑏′ if a, b are row vector 𝑎′∗𝑏 ifa,barecolumnvectors

Matrix Multiplication: Another example
>> a=[1 2 3]; >> b=[4 5 6]; >> dot(a,b) ans =
32
>> a*b’ ans =
32
>> a’*b
ans= 456
4 5 6 8 10 12
8 10 12 12 15 18 12 15 18
>> a=[1;2;3]; >> b=[4;5;6]; >> dot(a,b) ans =
32 >> a’*b
ans = 32
>> a*b’
ans =

Array Multiplication vs. Matrix Multiplication
For the multiplication of A and B
• Sizes
• Array multiplication: A and B should have the same size
• Matrix Multiplication: number of columns of A = number of rows of B
• Operators:
• Array multiplication: .* Matrix multiplication: *
>> A=[1 2 4; -3 0 7; 9 1 5]; B=[-1 3; -3 1; 1 0]; >> A*B
ans =
-3 5 10 -9 -7 28
>> A.*B
Error using .*
Matrix dimensions must agree.

Multiplication of matrices
Matrix operations
Properties
Properties of matrix multiplication:
1. Matrix multiplication is noncommutative
(order of addition does matter) AB  BA in general
• It may be that the product AB exists but BA does not (e.g. in the previous example C=AB is a 3×2 matrix, but BA does not exist)
• Even if the product exists, the products AB and BA are not generally the same

Multiplication of matrices
Matrix operations
Properties
2. Matrix multiplication is associative A(BC)= (AB)C
3. Distributive law
A(B + C)= AB + AC
(B + C)A = BA + CA
4. Multiplication by identity matrix
AI = A; IA = A
5. Multiplication by zero matrix A0 = 0;0A = 0

Array right division and array left division
A./B= 1/5 2/6 = 3/7 4/8
A.\B= 5/1 6/2 = 7/3 8/4
0.2 0.3333 0.4286 0.5000
53 2.333 2

Inverse matrix
ax=b.
How would you solve this equation for x?
Perhaps, you would divide both sides by a and obtain
Consider the equation
x=
b a

Inverse matrix
Here is another way to solve ax = b : Multiply both sides of the equation by
1a . ax=b 1ax=1b
the multiplicative inverse of a, i.e.
aa a a x = ba
1.x =
Hence, we conclude that
b
a
x = ba .

Inverse matrix
Suppose that a system of equations has the same number of variables as equations.
We convert it into a matrix equation of the
AX = B.
If the matrix A has an inverse, then we can solve for X and obtain
form
X = A−1B

Inverse matrix
Remember:
−1 X=AB
Since order matters in matrix multiplication,
X = BA−1
do not write

Example #1
Let
Multiply the two matrices on the left and use matrix equality to show that the given matrix equation is equivalent to a system of linear equations.
−2x+3y = 5 −4x+y = 8
−23×5   = 
−4 1y 8  

Example #2
Use your observations from the previous example to find matrices A, X, and B such
that the matrix equation
is equivalent to
the system of linear equations
2x+3y−z = −2 
AX = B x−y+z=8
3x−2y−9z = 9 

Example #2
AX = B
x−y+z = 8 2x+3y−z = −2
 
3x−2y−9z = 9 
1 −1 1
A=2 3 −1
3 −2 −9 
x
X =y
z 
8 
B=−2
9 

Example #2
Solve the system
x−y+z=8 2x+3y−z = −2

3x−2y−9z = 9 
1−11x 8 
A=2 3 −1, X=y, and B=−2
3 −2 −9 z 9 

Inverse matrix
X = A−1B.
How to calculate X with MATLAB?
4
 X = −3
 1  
X=inv(A)*B
or
X=A\B
We conclude that
x = 4, y = -3, and z = 1.
>> X=B/A
??? Error using ==> mrdivide Matrix dimensions must agree.

Inverse matrix and matrix division
• When you multiply a matrix and its inverse, you get the identity matrix.
3 −1 × 2 1 = 1 0 −5 2 5 3 0 1
• inv() function
• The inverse matrix of A : A-1=inv(A)
• Matrix right division A/B is defined as A*B^-1, or A*inv(B).
• Matrix left division A\B is defined as A^-1*B, or inv(A) * B.
• It is not B/A. B/A = B*A-1.

Example #3
Solve the system
 
123
A=1 1 0,X=x2,andB=5   
5x−x−x =0
x+x=5 12
 13
2x−3x =2 5 −1 −1 x 0
 1  
2 0 −3 x
 3 2


Example #3
X=inv(A)*B
or
 0.8125 
X =4.1875
We conclude that x1 = 0.8125,
x2 = 4.1875 x3 = -0.125
 − 0.125

X=A\B

Exercise

Exercise
AX = B
Step 1: create and initialize matrix A and column vector B.

Exercise
AX = B
Step 1: create and initialize matrix A and column vector B.
Step 2: calculate column vector x.
or
x=inv(A)*B
x=A\B

Exercise
AX = B
Step 1: create and initialize matrix A and column vector B.
Step 2: calculate column vector x.
or
Step 3: calculate A*X, and compare resultant array with B.
x=inv(A)*B
x=A\B

Common Array and Matrix Operations

Plotting
• MATLAB’s extensive, device-independent plotting capabilities are one of the most powerful features. They make it very easy to plot any data at any time.
• To plot a data set, just create two vectors containing the x and y values to be plotted and use the plot function

Plotting
• To plot a data set
• create two vectors of x and y coordinates of the dots to be plotted • use the plot function plot(x,y) to draw the curve
• Matlat draw the dots (based on x, y coorindates) and connect dots with lines
• Draw multiple curves in one figure
• two vectors (x and y coordinates) for each curve
• plot(x1, y1, x2, y2)
• plot(x, y1, x, y2) if x coordinates are shared (not plot(x, y1, y2))
• An optional attribute string can define up to 3 attributes • Three sets of attributes: color, Line style, Marker style
• plot(x1, y1, attr1, x2, y2, attr2)
• Use one or multiple characters to represent an attribute
• Other components in figures
• Title, xlable, ylable, legend, grid…

Plotting
Given data:
x y
1
2
3
5
7
7.5
8
10
2
6.5
7
7
5.5
4
6
8
Plot the given data in a figure.
>> x=[1 2 3 5 7 7.5 8 10]; >> y=[2 6.5 7 7 5.5 4 6 8]; >> plot(x,y)

Plotting
Plot a math function y=sin(2x)
x=0:pi/2:2*pi; y1=sin(2*x); plot(x,y1);
Which points were generated?

Plotting
1 0.8 0.6 0.4 0.2 0 -0.2 -0.4 -0.6 -0.8
x=0:pi/100:2*pi; y1=sin(2*x); plot(x,y1);
-10 1 2 3 4 5 6 7
How many points were generated?
>> length(x)

Line color & style, Marker style & Legends
• The line color, style and the type of marker used for data points on the line can be selected using an attribute string after the x and y vectors in the plot function.
• The attribute string can have up to 3 characters • one character specifying the color of the line.
• one character specifying the style of the marker.
• one character specifying the style of the line.
• Legend function
legend(‘string1’, ‘string2′,…,pos)

Plot the given data in a figure
Year
1988
1989
1990
1991
1992
1993
1994
Sales (M)
127
130
136
145
158
178
211
>> year = [1988:1:1994];
>> sales = [127, 130, 136, 145, 158, 178, 211];
>> plot(year,sales,’–r*’)
Attribute string : dashed red line and asterisk markers.

Drawing two curves on one figure
x=0:pi/100:2*pi; y1=sin(2*x); y2=2*cos(2*x); plot(x,y1,x,y2);
2 1.5 1 0.5 0 -0.5 -1 -1.5
-20 1 2 3 4 5 6 7

Add some attributes
Drawing two curves on one figure
x=0:pi/100:2*pi; y1=sin(2*x); y2=2*cos(2*x); plot(x,y1,’k-‘,x,y2, ‘b–‘);
2 1.5 1 0.5 0 -0.5 -1 -1.5
-20 1 2 3 4 5 6 7

Add some remarks
Drawing two curves on one figure
x=0:pi/100:2*pi;
y1=sin(2*x); y2=2*cos(2*x); plot(x,y1,’k-‘,x,y2, ‘b–‘);
title(‘Plot of sin(2x) and 2cos(2x) ‘); xlabel(‘x’); ylabel(‘y’); legend(‘sin(2x) ‘, ‘2cos(2x) ‘);
grid on;
Plot of sin(2x) and 2cos(2x)
2 1.5 1 0.5 0 -0.5 -1 -1.5
sin(2x)
2cos(2x)
-20 1 2 3 4 5 6 7
x
y

Plot Colors, Market Styles, and Line Styles

Using array operations when plotting a function
y=3.5−0.5x cos(6x) for −2x4
Creating a vector
Plot:
A script file for plotting the function is:
with spacing of 0.01.
3 2 1 0
-1 -2 -3
-2 -1 0 1 2 3 4
x = [-2:0.01:4];
y = 3.5.^(-0.5*x).*cos(6*x); plot(x,y)
Calculating a value of y for each x.

Multiple curves in the same figure
Generate x as a linearly spaced vector from -1.5 to 1.5 with 30 points. Let
y1 =x
y2 = power of 2 of x y3 = power of 3 of x y4 = power of 4 of x
Plot y1, y2, y3, and y4 versus x in the same figure.

Multiple curves in the same figure
x = linspace(-1.5, 1.5, 30); y1 = x;
y2 = x.^ 2;
y3 = x.^ 3;
y4 = x.^ 4;
plot(x,y1,x,y2,x, y3, x, y4) xlabel(‘x Value’)
ylabel(‘y Value’) title(‘Powers of x’) legend(‘y1’, ‘y2’, ‘y3’, ‘y4′)

Multiple curves in the same figure
Plot function, y = 3×3 − 26x +10 and its first and second derivatives in different colors, for−2 ≤ 𝑥 ≤ 4, all in the same plot.
𝑦 = 3𝑥3 − 26𝑥 + 10
𝑦𝑑 = 9𝑥2 − 26
𝑦𝑑𝑑 = 18𝑥

Multiple curves in the same figure
vector x —- the domain of the function. y = 3*x.^3-26*x+10; Vector y —- the function value at each x
yd = 9*x.^2-26; Vector yd —- values of the first derivative.
x = [-2:0.01:4];
ydd = 18*x; plot(x,y,’-b’,x,yd,’–r’,x,ydd,’:k’)
Vector ydd —- values of the second derivative.
Create three graphs in the same figure —- y vs. x (solid blue line), yd vs. x (dashed red line), and ydd vs. x (dotted black line).

Specify more attributes than 3
y=x2 −10x+15 for0x10, x=1
x=0:1:10; y=x.^2-10.*x+15; plot(x,y,’r–‘,x,y,’bo’);
x=0:1:10 y=x.^2-10.*x+15 plot(x,y)
15 15
10 10
55
00
-5 -5
-100 1 2 3 4 5 6 7 8 9 10 -100 1 2 3 4 5 6 7 8 9 10

Logarithmic scales
• ‘plot’ function plots both x and y data on linear axes.
• ‘semilogx’ function plots x data on logarithmic axes and y data on linear axes.
• ‘semilogy’ function plots x data on linear axes and y data on logarithmic axes
• ‘loglog’ function plots both x and y data on logarithmic axes.

Logarithmic scales
x=0:0.1:10; y=(x-5).^2; plot(x,y)
semilogx(x,y); semilogy(x,y); loglog(x,y);
25 25 20 20 15 15 10 10
55
00 5 100-1 0 1 10 10 10
102 102
100 100
10-2 10-2
0 5 1010-1 100 101

Figure function
figure(1); x=0:pi/16:pi*2; plot(x,sin(x)); figure(2); plot(x,cos(x));
Figure 1
1 0.8 0.6 0.4 0.2 0 -0.2 -0.4 -0.6 -0.8 -1
1 0.8 0.6 0.4 0.2 0 -0.2 -0.4 -0.6 -0.8 -1
01234567
Figure 2
01234567

What does a sound look like?
make a sound in MatLab
Fs = 44100;
t = [0:1/Fs:2]; %2 second,44100 samples freq = 400; % Hz
f1 = sin(2*pi*freq*t);
sound(f1,Fs); %play sound f1 at 400Hz
Plot it in MatLab
plot(t(1:500), f1(1:500)); Why can’t we use plot(t, f1)?

Exercise #1

Exercise #1
• Fill in correct code and replace the ellipses
g = -9.81;
v0 = input(…); h0 = input(…); t = 0:0.5:10;
h = …
v = …
plot( … );
title(…); xlabel(…); ylabel(…); legend(…); grid on;
optional

Exercise #1
Test the program with the initial velocity of the ball = 20, and the initial height of the ball = 10 :

Exercise #2

Exercise #2
Test the program
for (a) with two inputs:
If the input is 10 watts, the power in decibel is 40dBm; If the input is 0.1 watts, the power in decibel is 20dBm;
For (b), you may also use figure() function
• figure(): create a new figure window.
• To get help: help figure
• Draw figures for the power values 1:2:100

Exercise #2

Plot 6 figures in a window
subplot(m,n,p) breaks the Figure window into an m-by-n matrix of small axes, selects the p-th axes for the current plot, and returns the axes handle.
The axes are counted along the top row of the Figure window, then the second row, etc.
For example,
subplot(2,1,1), plot(income) subplot(2,1,2), plot(outgo)
plots income on the top half of the window and outgo on the bottom half.

Plot 6 figures in a window
clear
clc
close all
x = linspace(0, 2*pi, 10); subplot(2, 3, 1);
plot(x, sin(x));
subplot(2, 3, 2) plot(x, sin(x)) hold on
plot(x, cos(x))

Plot 6 figures in a window
subplot(2, 3, 3) plot(x, sin(x),’–‘) hold on
plot(x, cos(x), ‘r:’)
subplot(2, 3, 4)
N = 16;
xr = linspace(0, 1, N);
yr = xr + rand(1,N) – 0.5; plot(xr, yr, ‘r+’)
subplot(2, 3, 5)
x = 0:0.01:20;
y1 = 20*exp(-0.05*x).*sin(x); y2 = 0.8*exp(-0.5*x).*sin(3*x); plotyy(x,y1,x,y2,’plot’);
subplot(2, 3, 6)
pow = linspace(0, 1);
w = 10.^pow;
fr = complex(0, w);
h = (fr.^2 + 0.1*fr + 7.5) …
./ (fr.^4 + 0.12*fr.^3 + 9*fr.^2); loglog(w, abs(h))

Plot 6 figures in a window
111 0.5 0.5 0.5 000 -0.5 -0.5 -0.5
-10 5 10-10 5 10-10 5 10
1.5 1 0.5 0 -0.5
0
0.5 1
20 15 10
5
0 -5 -10 -15 -20
0
10
1 100
0.8
0.6
0.4 -1
0.120
0
-0.2
-0.4-2
-01.60 0 1 20 10 10

Table
Table is a data type suitable for column-oriented or tabular data that is often stored as columns in a text file or in a spreadsheet.
Tables consist of rows and column-oriented variables. Each variable in a table can have a different data type and a different size with the one restriction that each variable must have the same number of rows. For more information, see Create and Work with Tables or watch

Create Tables and Convert Type
table
array2table cell2table struct2table table2array table2cell table2struct table2timetable timetable2table
Table array with named variables that can contain different types
Convert homogeneous array to table Convert cell array to table
Convert structure array to table Convert table to homogeneous array Convert table to cell array
Convert table to structure array Convert table to timetable Convert timetable to table

Read and Write Files
readtable writetable
detectImportOptions spreadsheetImportOptions getvaropts
setvaropts
setvartype preview
Create table from file Write table to file
Create import options based on file content Import options object for Spreadsheets
Get variable import options
Set variable import options
Set variable data types
Preview eight rows from file using import options

Example
Create and Write Tables
• Create tables from csv file nasdaq.csv
• Create Tables with table()
• Write table to csv file

Advantages of using Tables
• Conveniently Store Mixed-Type Data in Single Container
You can use the table data type to collect mixed-type data and metadata properties, such as variable name, row names, descriptions, and variable units, in a single container. Tables are suitable for column- oriented or tabular data that is often stored as columns in a text file or in a spreadsheet. For example, you can use a table to store experimental data, with rows representing different observations and columns representing different measured variables.
Tables consist of rows and column-oriented variables. Each variable in a table can have a different data type and a different size, but each variable must have the same number of rows.

Access Data in Tables
• Using Numeric or Named Indexing
You can index into a table using parentheses(), curly braces{}, or dot
indexing.
Parentheses allow you to select a subset of the data in a table and preserve the table container.
Curly braces and dot indexing allow you to extract data from a table.
Within each table indexing method, you can specify the rows or variables to access by name or by numeric index.

Example
Access Data in Tables:
• Access data with (), • Access data with {} Output Class: table • Output Class: cell
• Access data with dot indexing • Output Class: cell

Example
Access Data in Tables:
• In addition to labeling the data, you can use row and variable names to access data in the table. For example, use named indexing to display the age and blood pressure of the patients Williams and Brown.
• Add RowNames

Table.Properties
• T.Properties, where T is a table, is a scalar struct containing the following table metadata:
• Structures and cell arrays do not have properties for storing metadata.

Example
Table.Properties:
To print a table summary, use the summary() function.

Add and Delete Table Rows
• Add Rows by Concatenation
• Add Rows from Cell Array

Add and Delete Table Rows
• Omit Duplicate Rows
• Delete Rows by Row Number • Delete Rows by Row Name
• Search for Rows to Delete

Add and Delete Table Variables
• Add Variables Concatenated from Another Table

Add and Delete Table Variables
• Add variables with function addvars()
• Add Variables Using Dot Syntax

Add and Delete Table Variables
• Use the removevars() function to delete Variables
• Delete Variable Using Dot Syntax
• Delete Variable Using Indexing

Calculation on Tables
• Find the Average Across • Use cellfun() Each Row

Calculation on Tables
• varfun()
• Access variables in Table and apply calculation for cell

Sort Rows & Select Rows with Logical Indexing
• Select Rows
• Sort Rows based on a variable

Exercise: Matlab programming for Homework 1 and 2
• Home work1
Write Matlab code to generate an email list for the students who
did not attend the class.
• Home work2-1
Read the historical price data of SPY and TLT from SPY.csv and TLT.csv. Calculate the average return, std of both ETFs and their covariance and correlation. Draw the efficient frontier of portfolios given the two risky assets.

Exercise: Matlab programming for Homework 1 and 2
• Home work2-2
Consider now you are a financial advisor. Your client consults you for his potential investment plan. He provides the following
parameters.
Initial pension money: $1,000,000
His yearly drawdown will be $100,000.
In year 5,6,7,8, he needs to have $50,000 more drawdown to pay for his daughter’s college tuition in New York University.
He is considering an investment portfolio with X% of stock (SPY) and 1-X% of riskless asset (yearly return 3%). You need to help him calculate what is the best X%. To simplify the problem, we specify, X has to be (0, 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90%, 100%).
For the future, we assume the return of SPY follows normal distribution with mean and std derived from those calculated in Q1. To simplify: we use the following formulas:
yearly mean = 250*daily mean yearly std = sqrt(250)*daily std
You are going to run a 50 Monte Carlo simulations for him.
The selection standard is:
1. for over 90% of the 50 simulations, he still has positive asset by the end of year 10.
2. The average remaining asset is the highest.