Lectures 1 & 2: MATLAB basics and programming
Lectures 1 & 2: MATLAB
basics and programming
Computational Finance
1
We’re Recording
We will only share this recording with this class section.
We will delete this recording at the end of the term.
2
At Carey since 2017
Bachelors from University of
Virginia
PhD from New York University
I research financial crises, and
how governments can prevent
or respond to them
• Requires me to write and solve
computationally complex models,
which I usually solve in MATLAB
A little bit about me
3
Pilates, swimming , soccer, fishing,
table tennis, snowboarding
FC Barcelona, NBA
Travel, delicious food
Video games, movies, TV series
Dancing, singing
Writing novels
Spending time with friends
A little bit about you
4
1 & 2: MATLAB Programming
3 & 4: Working with and analyzing data
5 & 6: Solving models with simulation
7: Advanced topics (time permitting)
Course Overview by Week
Writing computer programs to answer questions in finance
• E.g. How much should this security be worth?
• E.g. What predicts bankruptcy?
You will learn to
• How to write readable and efficient code
• Manipulate, visualize, and analyze real-world data
• Price financial portfolios using simulation
Why MATLAB?
• Easy-to-use and powerful language with a large library of built-in tools, great plotting
capabilities
• Excel is not enough.
• R/Python/Julia a little less beginner-friendly. But if you like this class, learn those
next!
• Let’s see an example!
6
What is Computational Finance?
Get comfortable creating, opening, modifying and running MATLAB scripts
Programming Best Practices
Commenting and Debugging
Displaying and Plotting Output
Arrays and Matrix Algebra
Controlling Code Flow
• Relational and logical operators
• If statements
• For loops
• Functions
7
Goals for the first two weeks
Getting
Started with
MATLAB
8
Right after starting MATLAB and before doing anything
else:
• Change to the directory you want to use
9
Choosing Your Current Directory &
Recording Your Command Window Session
Now we can create a file to record our command session
type: diary lecture_1.txt
Note that MATLAB files should never have spaces in the names
When we want to close this file, we will type: diary off
Assignment operator (pronounced “assign”): ‘=‘
• variable_name = a numerical value
• Example: stock_price = 32;
o note: ‘;’ suppresses output
Rules about variable names
• Letters, digits and the underscore character allowed
• Must begin with a letter
• Case-sensitive
• Allowed: s, stock, stock_price, s1
• Not allowed: 1s, s!, s*
10
Variables and Assignment Statements
What does this mean?
b = 6*exp(-.05*1) + 106*exp(-.05*2)
Compare to:
r = .05;
t = [1 2];
cash_flows = [6 106];
discounted_cash_flows = cash_flows.*exp(-r.*t)
bond_price = sum(discounted_cash_flows)
Readability is key to writing maintainable, understandable
code!
11
Meaningful Names and Readability
Keywords
• Reserved by Matlab for various purposes, and cannot be used for variable names
• Identify two ways:
• iskeyword()
• Command length(iskeyword)tells us that there are 20 keywords
• Keywords turn blue when typed: try typing ‘end’ in the command window
Predefined Matlab variables
• ans, pi, eps (the smallest difference between two numbers),
• i, j, NaN
Some useful commands
• who, whos, clear x, clear(‘x’,’y’,’z’), clear, clc
• Good time to take some notes…
12
Matlab variable considerations
Math Functions Rounding Functions
sqrt(x) – the square root of x round(x) – round to the nearest
integer
exp(x) – e to the power x ceil(x) – round up
log(x) – natural logarithm of x floor(x) – round down
log10(x) – log of x to the base 10
abs(-10) – absolute value
13
Some Built-in Functions
Trigonometric Functions Random numbers
sin(x) – sine rand() – generate a uniformly
distributed random number
cos(x) – cosine randn() – generate a normally
distributed random number
randi() – random integers between 1
and a specified maximum
• For functions (and variables,
as we will see later),
capitalization/case matters
• Type ‘doc
function_name’ on the
command line (no quotes, and
replace function_name)
for the description of a
function and usage
instructions, or search the
Matlab help
14
Working In the Command Window
Command Window Tricks Display Format
clc – clear the command window format short – default format
; – semicolon suppresses output format long – displays more digits
↑ – recall previously typed command format bank – displays whole
numbers plus two significant decimal
digits
↓ – navigate to more recent commands format – resets the format to default
; can also separate multiple commands on
one line (, does too but stick to 😉
(type ‘doc format’ for options)
(See command history window for
previous commands)
Everything working in the command window
also works in script files
From the command line: ‘edit
AssetReturn.m’
• or New Script from the menu
• Or Ctrl-N
In the script file that comes up, type:
15
Creating a Script File
clc; clear;
simple_return = 0.01;
log_return= log(1 + simple_return);
disp(‘Simple Return’);
disp(simple_return);
disp(‘ ‘);
disp(‘Log (compounded) Return’);
disp(log_return);
Editor Window
Command Window
Two ways to run
1. The green run button (after running from the green button, you can use the
up arrow from the command line to run again)
2. Type the name of the script on the command line
16
Running a Script File
Programmers spend more time debugging than initially writing
code
You will make mistakes. You will get errors. You’ll get (really) wrong
results.
How to fix? See what your code is doing at intermediate steps
1. Left-click the line number to Insert a breakpoint to examine variable
values at a particular step
2. Proceed through the code line by line to see if they change as you expect
17
Debugging: Finding and fixing mistakes
Type ‘doc disp’ in the command window
Help menu: search disp, copy the first example and run it
Examples:
disp(5); %displays the number 5
x=5; disp(x); %displays the value of variable x
disp(‘ ‘); % displays an empty line (space required between the quotes)
disp(‘show text in string’); %displays the text between the quotes
What is the text in green? It’s comments: pieces of text in a script that are not
executed
• In MATLAB, you indicate a comment with a percent (%) sign. Anything after isn’t executed.
• Comments are a must for readable code. They are how you explain to others reading your
code (and to yourself, months later!) what is going on
18
Displaying Outputs: the disp()Function
吴媚蓉
19
Displaying Outputs: fprintf()
fprintf() allows us to display a mix of text and numeric values in
specific formats
Example:
fprintf(‘An int: %3d; a float: %6.1f; a string: %s’, 5, 4.86362, ‘hello’);
The text is displayed as shown except for each ‘%’ denoting a “placeholder” for which
we must pass a corresponding value.
Search “Formatting text” in MATLAB’s help for a full explanation of format strings
Format Output Note
fprintf(‘%d’,5) 5
fprintf(‘%3d’,5) 5 Takes up 3 spaces total
fprintf(‘%.1f’,4.86362) 4.9 Rounded to 1 decimal
fprintf(‘%4.1f’,4.86362) 4.9 Takes up 4 spaces total
Let’s re-do our script file using fprintf()
Open a new script file and call it ‘AssetReturn2.m’
clc; clear;
simple_return = 0.01;
log_return= log(1 + simple_return);
fprintf(‘Simple Return: %g\n’,simple_return);
disp(‘ ‘);
fprintf(‘Log (compounded) Return: %g\n’,log_return);
The ‘\n’ is a special character specifying a new line
• The disp() function automatically includes a carriage return and newline, while the fprintf()
function does not.
• Try deleting ‘\n’ and running again. What’s different?
20
Using fprintf()
Work in pairs with the
person sitting next to you.
• Discuss your overall
approach first
• One person can code, the
other can watch and point
out errors
• Called “pairs programming”
• Switch for the next exercise
We will reconvene in 15
minutes
21
In-Class Exercise
Recall from Corporate Finance that that the present value of a cash flow
CF received t years from now when the t-year net interest rate is r equals
Write a program that uses this formula to compute the present values of
a $5,460 cash flow received 11 years from now if the interest rate is
1.65%.
Store the cash flow in a variable called CF. Store the years in a variable
called t. Store the interest rate in a variable called r. Perform the
calculation and store the present value in a variable called PV. Don’t
forget to end your lines with semicolons.
Use the disp command to display your result, along with a caption to
indicate what the number means. If you ended your lines with
semicolons, these two lines should be the ONLY thing displayed in the
command window.
https://en.wikipedia.org/wiki/Pair_programming
Suppose that a 2-year
Treasury bond with a
principal of $100 provides
coupons at the rate of 6%
per annum semiannually.
What is the price of this
bond?
See Calculate_BondPrice.m
22
Calculate Bond Price: Script File
Arrays and
matrix
algebra
23
MATLAB array is a generalization of
the mathematical concept of matrix
Vectors: Bond price example
• Time vector: [0.5, 1.0, 1.5, 2.0]
• Interest vector: [5%, 5.8%, 6.4%, 6.8%]
• Cash flow vector: [3, 3, 3, 103]
Terminology
• Row vector
• Column vector
• Transpose operator
24
What Is An Array?
Creating a vector from a list of
numbers
• Row vector:
[3 3 3 103]
or [3, 3, 3, 103]
o Up to you, but I prefer the syntax
with commas
• Column vector: [3; 3; 3;
103]
(note ; vs ,)
• Transpose operator: ‘
(apostrophe/single quote)
Creating a vector with known spacing
• Consider the time vector: [0.5, 1.0, 1.5,
2.0]. What if it needed to go to 30? A lot to type
by hand…
• t = 0.5:0.5:2.0;
o Start at 0.5
o Add elements incrementing by 0.5
o Until we reach 2.0
• What if you omit the second 0.5? Default
behavior is to increment by 1
o E.g. t = 1:5 gives you [1, 2, 3, 4, 5]
• Specify a 1×5 vector evenly spaced from 1 to 9?
o 1:?:9
Creating 1d arrays (Vectors)
25
Creating a vector by specifying the ends and the number of points
• linspace(1,9,5): 5 evenly-spaced numbers from 1 to 9
• linspace(1,9,6): 6 evenly-spaced numbers from 1 to 9
x:y:z versus linspace
• If you know what your increment is (e.g. half a year), use x:y:z
• If you know how many points you need, use linspace
26
Creating Vectors (Continued)
Math
• Consider the following matrix
7 4
3 8
6 5
• It has two dimensions: 3 rows and 2 columns – a 3 x 2 matrix
• In general, an m x n matrix has m row vectors or n column vectors
Matlab
• [7, 4; 3, 8; 6, 5]
• [v1; v2; v3] %v1, v2 and v3 are row vectors defined
earlier
• [1:2:9; 2:2:10]
• Transpose operator ‘ switches rows with columns
o What does [7, 4; 3, 8; 6, 5]’ look like?
27
Creating 2D arrays (Matrices)
Creating matrices quickly with special matrices in MATLAB
• zeros creates a matrix of all zeroes
• ones creates a matrix of all ones
• eye creates an identity matrix: ones on the diagonal and zeros
elsewhere
o Math question: what makes the identity matrix special?
All variables in MATLAB are arrays
• Scalar, 1×1
• Row vector, 1xm
• Column vector, nx1
• Matrix, mxn
28
Creating Matrices (Cont.)
Vector: v(n) retrieves the n’th element of the vector v, whether row or column
2D array: a(m,n) retrieves the element in the m’th row and n’th column
Colon (‘:’) operator
• Vector: v(:), v(n1:n2)
• Matrix:
o Row m: a(m,:)
o Column n: a(:,n)
o Other usage in the book (page 44)
end operator
• v(end)
• a(1,end), m(end,1), a(end,end)
• a(:,end), a(end,:)
Built-in functions for arrays
• length(v) – the number of elements in the vector v
• size(a) – the size of the array a, mxn 29
Array Addressing: Referring to a part of an array
Addition and subtraction (must be the same size)
• Vector addition and subtraction
o v1=1:5; v2=5:-1:1; v3=v2+v1
o v4=11:15; v5=v4-v1;
• Matrix addition and subtraction
o a1 = [v1;v2]; a2 = [v3;v2]; a3 = a1+a2;
o a4 = a2-a1;
Element-by-element (“element-wise”) operations
(arrays must be the same size or one must be a
scalar)
• Multiplication (.*): a5=2*ones(2,5); a6=a5.*a1;
• (right) Division (./): a7 = a6./a1;
• Exponentiation (.^): a8=a1.^2; 30
Matrix Operations
Matrix multiplication is a mathematical concept from
linear/matrix algebra
• This is not an element-by-element operation
• Vector example: a (1×3) vector * a (3×1) vector
31
Matrix Multiplication (* – no .)
4 5 6 ∗
1
2
3
= 4 ∗ 1 + 5 ∗ 2 + 6 ∗ 3 = 32
‘Inner’ dimensions
must match
Outer dimensions determine the size of the resulting matrix
In MATLAB, this is:
[4, 5, 6] * [1, 2, 3]’
8 1 2
−5 6 7
∗
−5 1
0 2
−11 7
32
Matrix Multiplication: Animated Example
8 1 2
−5 6 7
2×3
∗
−5 1
0 2
−11 7
3×2
33
Matrix Multiplication: Animated Example
8 1 2
−5 6 7
2×3
∗
−5 1
0 2
−11 7
3×2
34
Matrix Multiplication: Animated Example
3 equals 3
8 1 2
−5 6 7
2×3
∗
−5 1
0 2
−11 7
3×2
=
2×2
35
Matrix Multiplication: Animated Example
8 1 2
−5 6 7
∗
−5 1
0 2
−11 7
=
36
Matrix Multiplication: Animated Example
8 1 2
−5 6 7
∗
−5 1
0 2
−11 7
=
8 −5 +
37
Matrix Multiplication: Animated Example
8 1 2
−5 6 7
∗
−5 1
0 2
−11 7
=
8 −5 + 1 0 +
38
Matrix Multiplication: Animated Example
8 1 2
−5 6 7
∗
−5 1
0 2
−11 7
=
8 −5 + 1 0 + (2)(−11)
39
Matrix Multiplication: Animated Example
8 1 2
−5 6 7
∗
−5 1
0 2
−11 7
=
8 −5 + 1 0 + (2)(−11) 8 1 + 1 2 + (2)(7)
40
Matrix Multiplication: Animated Example
8 1 2
−5 6 7
∗
−5 1
0 2
−11 7
=
8 −5 + 1 0 + (2)(−11) 8 1 + 1 2 + (2)(7)
41
Matrix Multiplication: Animated Example
8 1 2
−5 6 7
∗
−5 1
0 2
−11 7
=
8 −5 + 1 0 + (2)(−11) 8 1 + 1 2 + (2)(7)
−5 −5 + 6 0 + (7)(−11)
42
Matrix Multiplication: Animated Example
8 1 2
−5 6 7
∗
−5 1
0 2
−11 7
=
8 −5 + 1 0 + (2)(−11) 8 1 + 1 2 + (2)(7)
−5 −5 + 6 0 + (7)(−11) −5 1 + 6 1 + (7)(7)
43
Matrix Multiplication: Animated Example
8 1 2
−5 6 7
∗
−5 1
0 2
−11 7
=
8 −5 + 1 0 + (2)(−11) 8 1 + 1 2 + (2)(7)
−5 −5 + 6 0 + (7)(−11) −5 1 + 6 1 + (7)(7)
= −62 24
−52 56
44
Matrix Multiplication: Animated Example
Try this example:
X = [8,1,2;-5,6,7];
Y = [-5,1;0,2;-11,7];
X_times_Y = X*Y
If the inner dimensions did not match (e.g. if Y had a
fourth row), you will see this error:
45
Matrix Multiplication (with matrices)
Using arrays in Matlab built-in math functions (element-by-
element)
• sqrt(a8)
• x=linspace(-2*pi,2*pi); y=sin(x); plot(x,y);
Built-in functions for analyzing arrays
• sum(v): v=1:9; sum(v)
• max(a): a = round(9*rand(5)+1); max(a)
• min(a)
• mean(v): v=randn(1000,1); mean(v);
• std(v);
• Note the dim parameter in the help pages for array functions.
o This determines whether it operates down the first dimension or across the second
dimension in a two-dimensional matrix
o Try: disp(max(a,[],2)); and disp(max(a,[],1));
46
Functions and Arrays
Work in pairs with the
person next to you
If you “drove” the
code last time, it’s
your turn to
“navigate.” And vice
versa.
We will reconvene in
15 minutes
47
In-Class Exercise
Write a program that uses the present value formula to compute the total
(sum) of the present values of
1. a $5,460 cash flow received 11 years from now,
2. a $7,119 cash flow received 13 years from now, and
3. a $10,250 cash flow received 16 years from now,
discounting each cash flow at the interest rate of 1.65%.
Hint: redefine some of the variables you created for the first In-Class
Exercise to be vectors instead of scalars.
Use the disp command to display your result.
Let’s use Matlab arrays to write more readable and more efficient
versions of the example we looked at
• Calculate_BondPrice_vectorized.m
Can we modify these examples to use matrix multiplication instead of
elementwise multiplication and sum?
48
Examples
Relational
and Logical
Operators
49
Recall: + – * / ^ .* ./ .^ are all arithmetic operators.
• They perform arithmetic operations.
• Take two arrays of numbers (or just one: e.g. y = -x)
• Return an array of numbers
Relational operators perform comparisons
• Take two arrays of numbers
• Return an array of “logicals” (true or false)
• E.g. Is 5 greater than 3? Is 7 equal to 8?
Logical operators
• Take one or two arrays of logicals
• Return an array of logical
• E.g. are both statements true?
50
Relational and logical operators
Relational operators compare arrays. Are they equal? Is one
greater than the other?
>, <, >=, <=, ==, ~=
Return true (1) or false (0)
Double-equals (==) is a relational operator testing for equality
• E.g. 5==5 returns true, 5==3 returns false
• Different from the assignment operator (=) which assigns the right-hand side to the left-hand side
• E.g. a=5 sets value of a to 5. It does not test if an existing variable a is equal to 5! Very common
mistake.
Element-by-element comparison for arrays (same size)
• [5,3] == [5,4] returns [true, false]
51
Relational Operators
and &: are both true?
or |: is at least one true?
not ~: the opposite
If a logical operation is performed on a
number, MATLAB implicitly converts the
number to a logical: any nonzero value is
treated as true, zero is false
Element-by-element for arrays (same size)
Order of precedence:
• Parentheses
• Arithmetic
• Relational
• Logical
• When in doubt, use parentheses!
X Y X & Y X | Y ~X
true true true true false
true false false true false
false true false true true
false false false false true
Logical Operators
52
What does each of the following return? True or false?
1 & 1, 1 & 0, 5 & 0,
1 | 1, 1 | 0, 5 | 0, 0 | 0,
~1, ~5
Use an array of true/false to extract elements out of another array
v1 = [ 4, 7, 11, 23];
v2 = [ true, false, false, true];
v1(v2) outputs [4, 23]
• The elements in v1 that correspond to true in v2
Useful way to extract elements of an array that match a certain
condition
• Recall: v1 > 10 returns [false, false, true, true]
• So v1(v1 > 10) returns [11, 23]
53
Logical Indexing
Control
statements
54
In most soccer leagues, a team gets
• 3 points for a win
• 1 points for a tie (draw)
• 0 points for a loss
Example: Chelsea 3 – 1 Liverpool
• How many points do Chelsea get? Liverpool?
Example: Manchester City 2 – 2 Manchester United
• How many points do City get? United?
How do we write a MATLAB program that can “award” points to
teams based on the score?
55
Soccer example
Direct the execution of the program depending on whether a condition is
true or not. If true, do one thing. If false, do something else.
if-end
if-else-end
56
Conditional Statements
Note: the code after if must produce a
logical (true or false) scalar, not an array!
Think about it: “If true, do X” makes sense.
“If true false true true, do X” doesn’t.
If-elseif-else-end: If one condition is true, do one thing. If the first
condition is false but another condition is true, do some other thing.
If neither is true (both are false), do something else.
Switch-case statement
• Short-hand method to implement a long series of elseif statements
• See the book for this; we won’t use it for now
57
Conditional Statements (Cont.)
disp(1)
disp(2)
disp(3)
disp(4)
disp(5)
versus
for i = 1:5
disp(i)
end
What you’re telling the computer:
• Set i to 1.
• Do whatever is in between for
and end
o In this case, display the value of i
• Increment i by 1 to 2
• Do whatever is in between for
and end
• …
• Increment i by 1 to 5
• Do whatever is in between for
and end
• Leave the loop.
What if the first line was
for i = 1:2:5
For Loops
58
Suppose we want to calculate the value of Firm A’s debt for a
range of possible asset values from $0 to $100 in order to make
the graph we saw? See soccer_points.m
59
Loops: perform same calc for multiple values
Make the graph: plot(score_differentials,points,’o’)
We’ll talk more about making plots later
-5 -4 -3 -2 -1 0 1 2 3 4 5
Score Differential
-1
0
1
2
3
4
P
oi
nt
s
R
ec
ei
ve
d
Points Awarded for Soccer Match Results
Recall that the real roots of a quadratic equation 𝑎𝑎𝑥𝑥2 + 𝑏𝑏𝑥𝑥 + 𝑐𝑐 = 0
are given by
𝑟𝑟 = −𝑏𝑏± 𝐷𝐷
2𝑎𝑎
where 𝐷𝐷 = 𝑏𝑏2 − 4𝑎𝑎𝑐𝑐 ≥ 0
Write a script file that finds the roots for any a, b, and c
• If D > 0, report the values of both roots
• If D = 0, report the value of the sole root
• If D < 0, display a message saying that no real roots exist
Set a = 2, c = 2, and try 8, 4, and 3 as values for b
Work in pairs. We will reconvene in 15 minutes
61
In-Class Exercise: Quadratic Formula
Making
Plots
62
Open a new blank figure window
for plotting: figure
2D plot function: plot(X,Y)
Plot options: markers, line type,
color, line thickness, etc.
Never stop there! What is being
plotted? Axis labels, titles, etc.
Two plots in the same figure
window:
• hold on
• legend('first','second');
Two-Dimensional Plot
63
-5 0 5
x
-20
0
20
40
60
80
100
f(x
)
Roots of a Quadratic Equation
y=2.0 x
2
+ 8.0 x + 2.0
y=0
See script file: plot2figs.m
64
Other Plot Functions
Function Description
close all Closes all figures
figure Creates a new, blank figure window. Using figure(n) allows you to refer to
figure windows by number
hold ‘hold on’ plots all succeeding plot calls on the same window
‘hold off’ turns off the hold
legend Displays a legend box in the figure window
grid Displays grid lines on the plot
histogram(X):
Histogram of vector X
-4 -2 0 2
0
20
40
60
80
100
120
140
mesh(X,Y,Z) and contour(X,Y,Z):
3-D plots
Other Types of Plots
65
-2 -1 0 1 2
-2
-1.5
-1
-0.5
0
0.5
1
1.5
2
Demo
Mortgage Amortization
Schedule
66
Suppose you are buying a house for $513,500
You can afford a down payment up to $150,000 and expect to live in the house for
approximately 5 years
You contact the bank for a 30-year fixed rate mortgage and get the following rate
schedule:
• LTV up to 80%: 0 points, 2.65% annual rate
• LTV up to 80%: 1 point, 2.5% annual rate
• LTV above 80%: 0 points, 2.9% annual rate
Terminology:
• LTV ("loan to value"): loan amount / house value = 1 – down payment / house value
• Point: percent of the loan amount payable as a fee when borrowing
How do you pick your down payment and loan?
67
How to pick a mortgage?
Choice of mortgage affects
• How much you must pay today
• How much you must pay every month going forward
• Remaining principal balance when you sell
Payment today = down payment + fees
Monthly payment 𝑃𝑃𝑃𝑃𝑃𝑃 depends on the annuity formula
𝐵𝐵0 = �
𝑠𝑠=1
𝑁𝑁
𝑃𝑃𝑃𝑃𝑃𝑃
(1 + 𝑟𝑟)𝑠𝑠
= 𝑃𝑃𝑃𝑃𝑃𝑃
(1 − 1 + 𝑟𝑟 )−𝑁𝑁
𝑟𝑟
What is the payment that needs to be made every month for the next 30 years
such that the sum of present values of all the payments discounted at the
mortgage rate equals the loan amount?
What is N? r? 𝐵𝐵0?
68
Constructing an Amortization Schedule
吴媚蓉
Choice of mortgage affects
• How much you must pay today
• How much you must pay every month going forward
• Remaining principal balance when you sell
Remaining principal balance depends on how much principal you have already repaid through your
monthly payments?
How much of your monthly payments go towards principal? How much go towards interest? Keeps
changing even though monthly payment stays fixed! Need to construct an amortization schedule:
Payment PMT
• Month 1
o Interest component: 𝑟𝑟𝐵𝐵0
o Principal component: 𝑃𝑃𝑃𝑃𝑃𝑃 − 𝑟𝑟𝐵𝐵0 reduces principal so that 𝐵𝐵1 = 𝐵𝐵0 − (𝑃𝑃𝑃𝑃𝑃𝑃 − 𝑟𝑟𝐵𝐵0)
• Month 2
o Interest component 𝑟𝑟𝐵𝐵1
o Principal component: 𝑃𝑃𝑃𝑃𝑃𝑃 − 𝑟𝑟𝐵𝐵1 reduces principal so that 𝐵𝐵2 = 𝐵𝐵1 − (𝑃𝑃𝑃𝑃𝑃𝑃 − 𝑟𝑟𝐵𝐵1)
As time goes by, is the interest component getting bigger? Is principal?
Let's build this in MATLAB 69
Constructing an Amortization Schedule
吴媚蓉
吴媚蓉
Lectures 1 & 2: MATLAB basics and programming
Slide Number 2
A little bit about me
A little bit about you
Course Overview by Week
What is Computational Finance?
Goals for the first two weeks
Getting Started with MATLAB
Choosing Your Current Directory & Recording Your Command Window Session
Variables and Assignment Statements
Meaningful Names and Readability
Matlab variable considerations
Some Built-in Functions
Working In the Command Window
Creating a Script File
Running a Script File
Debugging: Finding and fixing mistakes
Displaying Outputs: the disp()Function
Displaying Outputs: fprintf()
Using fprintf()
In-Class Exercise
Calculate Bond Price: Script File
Arrays and matrix algebra
What Is An Array?
Creating 1d arrays (Vectors)
Creating Vectors (Continued)
Creating 2D arrays (Matrices)
Creating Matrices (Cont.)
Array Addressing: Referring to a part of an array
Matrix Operations
Matrix Multiplication (* - no .)
Matrix Multiplication: Animated Example
Matrix Multiplication: Animated Example
Matrix Multiplication: Animated Example
Matrix Multiplication: Animated Example
Matrix Multiplication: Animated Example
Matrix Multiplication: Animated Example
Matrix Multiplication: Animated Example
Matrix Multiplication: Animated Example
Matrix Multiplication: Animated Example
Matrix Multiplication: Animated Example
Matrix Multiplication: Animated Example
Matrix Multiplication: Animated Example
Matrix Multiplication: Animated Example
Matrix Multiplication (with matrices)
Functions and Arrays
In-Class Exercise
Examples
Relational and Logical Operators
Relational and logical operators
Relational Operators
Logical Operators
Logical Indexing
Control statements
Soccer example
Conditional Statements
Conditional Statements (Cont.)
For Loops
Loops: perform same calc for multiple values
In-Class Exercise: Quadratic Formula
Making Plots
Two-Dimensional Plot
Other Plot Functions
Other Types of Plots
Demo
How to pick a mortgage?
Constructing an Amortization Schedule
Constructing an Amortization Schedule