COMP2022 Programming for FinTech Applications
Spring 2020
Professor: Dr. Grace Wang April 17 2020 Friday
1
1
Agenda
qFinish the last part about R: trading anomaly qProject description
qMatlab
2
2
1
Trading: TA or FA?
qTA: price (and volume) pattern
qhttps://school.stockcharts.com/doku.php a very good resource
qTo trade:
§ Entry and Exit § Trading signal? §Target
§ Stop loss
3
3
Trading: TA or FA?
qFA: fundamentals
qTrading on anomalies
§ Many of the anomalies are based on accounting variables or ratios.
§ Explanations as to why an anomaly exists often relate to investors not fully
understanding a particular accounting item, or not paying sufficient attention
to a key number or ratio.
§ Any accounting items and ratios that might be associated with a stock market anomaly?
4
4
2
Detecting anomalies
qWhat variable or ratio would you recommend looking at? How is it calculated? Is the data available?
qWhy do think this variable might be associated with a stock market anomaly?
qWhy do investors not pay sufficient attention to this variable, or fail to fully appreciate the meaning of the variable?
qWhat would your trading strategy be? Long which stocks, short which stocks. Why?
5
5
An example: The Bargain Power
qNote: Here is not to describe a working trading strategy, but stimulate you to think about potential trading strategies.
6
6
3
Related Variables
CRSP/COMPUSTAT
Accounts payable
AP
Accounts receivable
ARC
Cash
CH
COGS
COGS
Sales
SALE
Intuitions
qLooks for companies with increasing (decreasing) bargaining power with suppliers/customers
qProxy for bargain power with suppliers: (Accounts payable/COGS)*(cash/COGS)
qProxy for bargain power with customers: Accounts receivable/sales
7
7
Trading Strategies
qLong portfolio with high positive changes in
(Accounts payable/COGS) * (cash/COGS) / (receivable/sales)
qShort portfolio with negative changes in
(Accounts payable/COGS) * (cash/COGS) / (receivable/sales)
8
8
4
Another idea: increasing profit margin
qVariable: gross profit/sales (GP/SALE in compstat)
§ Long companies with very positive large changes in profit margin
§ Short matching companies with decreasing low profit margin (matching refers to the similar asset turnover and leverage)
9
9
Another idea: increasing operating efficiency
qlow profit margin but high turnover: efficient traditional company like Walmart (SALE/AT)
§ Long companies positive CF and very high turnover § Short matching companies with low turnover
10
10
5
Matlab
qConstants, operating constants qVariables
qScripts
11
11
Constant Values
qIntegers
§1, 12, 100, …
qReal numbers §1.35, 0.0024
qNumbers with signs § -17, -0.0403
qComplex numbers
§ Will be introduced later.
12
6
Scientific notation
qScientific notation is a way of writing numbers that are too big or too small to be conveniently written in decimal form.
qbase×10exponent § 2×106
qin matlab: base e exponent § 2e+6
decimal notation
scientific notation
MatLab
4,321.8
4.3218×103
4.3218e+03
6,720,000,000
6.72×109
6.7200e+09
0.000 000 007 51
7.51×10−9
7.5100e-09
13
Constant Values with Names
A constant is a value that remains unchanged. System Dependent
Infinity is produced by operations like dividing by zero, eg. 1.0/0.0, or from overflow, eg. 2*10^308.
A NaN is obtained as a result of mathematically undefined operations like 0.0/0.0 and inf-inf.
14
7
Constant Values with Names
q Several special functions provide values of useful constants. System Dependent
Euler’s number (e) ? exp(1) exp(2) = (exp(1))^2
15
Commonly used MATLAB functions
qsin — sine qcos — cosine
qtan — tangent
qexp — exponential
qlog — natural logarithm
qlog10— common (base 10) logarithm qlog2 — logarithm with base 2
16
8
Commonly used MATLAB functions
>> sin(0) >> cos(0)
ans =
ans = 01
>> sin(pi/6)
ans =
0.5000
>> sin(pi/2)
ans =
1
>> cos(pi/3)
ans =
0.5000
>> tan(pi/4)
ans =
1.0000
17
Get help in MATLAB
• help + topic_name (e.g. command, function) >> help sin
>> help clc
• doc + topic_name (e.g. command, function) >> doc sin
>> doc clc
18
9
Evaluate the following expression in MATLAB
sin 𝜋 +cos(𝜋) 12 12
>> sin(pi/12)+cos(pi/12) ans =
1.2247
Use parentheses to enclose input parameters
19
sin2(p /12)+cos2(p /12)
>> (sin(pi/12))^2+(cos(pi/12))^2
ans =
1
>> sin(pi/12)^2+cos(pi/12)^2
ans =
1
Integral part
20
10
sin(p /12)2 +cos(p /12)3 Wrong!
>> sin(pi/12)^2+cos(pi/12)^3
ans =
0.9682
>> (sin(pi/12))^2+(cos(pi/12))^3 ans =
0.9682
Correct Way:
>> sin((pi/12)^2)+cos((pi/12)^3) ans =
1.0683
21
tan(p / ln12)
>> tan(pi/log(12))
ans =
3.1595
22
11
æ æ5+cos(p )ö ö çè3ø÷
25-ç100-7eç ÷ ÷ èø
>> 25-(100-7exp(5+cos(pi/3)))
??? 25-(100-7exp(5+cos(pi/3)))
|
Error: Unexpected MATLAB operator.
You will get an error message. Use the up-arrow to bring this line back and then use the left and right arrow keys to correct the error(s).
23
æ æ5+cos(p )ö ö çè3ø÷
25-ç100-7eç ÷ ÷ èø
>> 25-(100-7*exp(5+cos(pi/3))) ans =
1.6378e+003
24
12
More exercises…
100″/& + 5×7 − 99 >>100^(3/2) + (5*7 – 99)/2 2 ans = 968
(3.2 + 1.65)!+ 165″/$%&($) 8
>> (3.2+1.65)^3+165^(4/(5*log(5)))/8
ans = 115.6659
5.48! + 1.65″ + 16#/%
7sin( 𝜋 ) 10
>> 5.48^8+1.65^3+16^(4/5)/(7*sin(pi/10))
ans = 8.1330e+05
25
Variables
26
13
Variables
qCreate a variable
qCheck the value of a variable qRemove a variable
qUse variables, change values qSave variables
27
Variables and variable names
qA variable is a value that may change.
qVariable name: each variable has a name.
qThe value is used when an expression is evaluated.
>> x=1 x=
1
>> y=x+1 y=
2
28
14
Variables and variable names
qVariables are organized in workspace.
§ Double click to examine a variable (value and properties)
§ whos command to list variables (names, values, and other properties).
qIn MatLab, a variable is a holding place for a value
qThe ans variable
§ans—- answer
§ is used in MATLAB as the default variable name when none is specified
29
3 4
1
2
4
30
15
Are they legal variable names?
qmax3
q3max
qmax_3
qmax 3
q[radius] qThe_Area_of_a_Circle q_Area_of_a_Circle
Are they same variables?
• Max3 and max3
• The_Area_of_a_Circle and The_Area_Of_A_Circle
31
Reserved Word
• It’s a good programming practice not to use the following reserved words as variable names
32
16
Avoid…
qReusing constant names § pi=1
§ i=2 §…
qReusing function names § sin=2
§ cos=3 §…
qWhat will happen?
Check workspace for new variables
§ Variables are created to save the (new) values. Future references by the names will use the values in variables, instead of the constants.
§ The functions will become inaccessible.
33
Avoid…
qWhat will happen?
§ Variables are created to save the (new) values. Future references by the names will use the values in variables, instead of the constants.
§ The functions will become inaccessible.
>> sin(0)
>> cos(pi)
>> tan(pi)
34
17
How to reset constants / functions?
qRestart MatLab
§MatLab resets the constants/functions when it is launched.
qUse clear command, e.g., §clear pi
§clear sin
35
Use meaningful names
qWill make your program easier to § Read
§ Understand § Debug
qCompare the following two cases. Which one is more clear?
Case 1:
a=0.1 radius=0.1
Case 2:
b=0.5 c=pi*a^2 d=c*b
length=0.5 area=pi*radius^2 volume=area*length
36
18
Remove variables
qInteractively, in workspace window §Select variables and hit “delete” key
qIn command window or in your program §Use clear command
üclear
üclear variable_name
§For more information: help clear
37
Variables
qCreate a variable
§ Give it a name and assign it a value.
qCheck the value of a variable § Use its name
§ Workspace window § whos command
qRemove variables
qUse variables, change values
38
19
Use variables in expressions
radius=0.1 length=0.5 area=pi*radius^2 volume=area*length
MatLab knows the value of a variable.
MatLab DOES NOT memorize how the value was calculated.
x=1 y=x*2
x=2
y y=x*2
Now y is 4.
Is y equal to x*2 = 4 now? How to update y’s value?
39
Variables
qCreate a variable
§ Give it a name and assign it a value.
qCheck the value of a variable § Use its name
§ Workspace window § whos command
qRemove variables
qUse variables, change values qSave variables
40
20
Save/load variables
qThe save command
§ save test.mat
üsave all the variables in current workspace into a data file named test.mat
§ save test.mat var1
üSave the variable named var1 into test.mat
§ save test.mat var1 var2
üSave the variables named var1 and var2 into test.mat
qThe load command § load test.mat
üload all the variables in test.mat into the workspace § load test.mat var1
üload the variable named var1 from test.mat § load test.mat var1 var2
üload the variables named var1 and var2 from test.mat
qIn workspace window, right-click the selected variables and choose “save”
41
>> radius=0.1
radius =
0.1000
>> length=0.5
length =
0.5000
>> area=pi*radius^2
area =
0.0314
>> volume=area*length
volume =
0.0157
>> radius=0.2
radius =
0.2000
>> length=0.5
length =
0.5000
>> area=pi*radius^2
area = 0.1257
>> volume=area*length
volume =
0.0628
42
21
>> radius=0.4
radius =
0.4000
>> length=0.5
length =
0.5000
>> area=pi*radius^2
area =
0.5027
>> volume=area*length
volume =
0.2513
Is there an easier way?
43
Scripts
44
22
Scripts
qA script: a group of commands to be executed together
qCreate a script
§ Click “new script” button
§ Type in the commands into the editor window
§ Save the commands with a .m filename extension
üScript file (.m suffix), e.g. cylinder.m
üFollow the same rules as those for variable names
qrun a script
§ Type the name (without the .m extension) in the command window
45
Run a script
Cylinder.m
Commands to run the script in command window
radius=0.1
Cylinder
radius=0.2
Cylinder
radius=0.4
Cylinder
length=0.5
area=pi*radius^2
volume=area*length
46
23
Initializing variables with keyboard input
input()
eg: in1 = input(‘Enter data: ‘); Enter data: 1.23
àstores the value 1.23 into in1
in2 = input(‘Enter data: ‘, ‘s’);
Enter data: 1.23
àstores the character string ‘1.23’ into in2
variable_name = input(‘prompt’)
47
disp( )
qdisplay text, constant, or variables qSyntax
§ disp(X)
qWhen disp(X) displays a variable, it does not print the variable name.
disp(“PolyU”) disp(5) disp(pi)
48
24
Semicolon (;) and comma (,)
qWhen placed at the end of a command, the semicolon tells MATLAB not to display any output from that command.
qYou can enter more than one MATLAB command on a line by separating each command with a semicolon or a comma.
qMATLAB suppresses output for those commands terminated with a semicolon, and displays the output for commands terminated with a comma.
>>A=12.5; B=42.7, C=1.25; B=
42.7000
49
Naming your file is very IMPORTANT
qIn Matlab, the script filename must be with .m. § Examples of Correct Names:
ünewtonsmethod.m üNewtonsMethod.m üNM12.m ücircle_area.m
§ Example of Incorrect Names:
ünewtonsmethod – Must have the “.m” extension.
ünewtons method.m – No spaces are allowed in script names.
üif.m, pi.m, cos.m – Not recommended, same name as reserved word/ constant/function.
üarea.m – Not allowed if area is a variable in the script file
qWhen running the program in the command window, you must use the name that is exactly (case sensitive) identical to the script file name without the .m extension!
50
25
Ex 1: bottom areas and volumes of cylinders
q Create a script to calculate § the area of the bottom:
area = pi * r ^ 2
§ the volume enclosed in the cylinder: volume = area * h
q Save the script into cylinder.m
q Execute the script from command prompt in the command window to calculate areas and volumes for r=h=1, r=h=10, and r=h=15
51
Cylinder.m:
command window:
area=pi*r^2
volume=area*h
>> r=1,h=1 >> Cylinder >> r=10,h=10 >> Cylinder >> r=15,h=15 >> Cylinder
>> r=1
>> h=1
>> Cylinder
>> r=10
>> h=10
>> Cylinder
>> r=15
>> h=15
>> Cylinder
>> r=1;h=1; >> Cylinder >> r=10;h=10; >> Cylinder >> r=15;h=15; >> Cylinder
52
26
Cylinder.m:
r=input(‘Please provide a radius:’);
h=input(‘Please provide a height:’);
area=pi*r^2;
volume=area*h;
disp(area);
disp(volume);
Can also display some text. Will be covered later.
In command window:
>> Cylinder
53
Ex: Celsius (°C) / Fahrenheit (°F) Conversion
qThere are two main temperature scales:
§ °F, the Fahrenheit Scale (used in the US), and
§ °C, the Celsius Scale (part of the Metric System, used in most other countries)
qThey both measure temperature, but use different numbers:
§ Boiling water (under normal conditions) measures 100° in Celsius, but 212° in Fahrenheit
§ And as water freezes it measures 0° in Celsius, but 32° in Fahrenheit
Celsius to Fahrenheit
F=C×9/5 +32
Fahrenheit to Celsius
C = (F – 32) x 5/9
54
27
qWrite a script (f2c) to convert a Fahrenheit degree to Celsius degree
qUse input() to accept inputs and disp() to show results.
§ variable = input(‘some text’); Single quotation marks § disp(variable/text/expression); around text
§ Put a semicolon (;) at the end of each command to suppress
output.
qTo test you code, convert the following degrees
Fahrenheit to Celsius
C = (F – 32) x 5/9
°C
100
40
37
30
21
10
0
-40
°F
212
104
98.6
86
69.8
50
32
-40
Description
Water boils
Hot Bath
Body temperature
Beach weather
Room temperature
Cool Day
Freezing point of water
Extremely Cold Day (and the same number!)
55
f2c.m
f=input(‘Input a Fahrenheit degree:’);
c=(f-32)*5/9;
disp(c);
56
28
q Write the other script (c2f) to convert a Celsius degree to Fahrenheit degree.
qUse input() to accept inputs and disp() to show results.
§ variable = input(‘some text’);
§ disp(variable/text/expression);
§ Put a semicolon (;) at the end of each command to suppress output.
qTo test you code, convert the following degrees
Celsius to Fahrenheit
F=C×9/5 +32
°C
100
40
37
30
21
10
0
-40
°F
212
104
98.6
86
69.8
50
32
-40
Description
Water boils
Hot Bath
Body temperature
Beach weather
Room temperature
Cool Day
Freezing point of water
Extremely Cold Day (and the same number!)
57
c2f.m
c=input(‘Input a Celsius degree:’);
f=c*9/5+32;
disp(f);
58
29
Ex: Pizza value
Pizza prices are typically listed by diameter. Write a program to compute a pizza’s unit value (cost per unit area, e.g. dollar per square inch), given the diameters and costs below.
Size
Price
Unit value (dollar per square inch)
Small Pizza – 10 inches
6.99
Medium Pizza – 12 inches
8.99
Large Pizza – 14 inches
10.99
Extra Large Pizza – 16 inches
12.99
59
diameter=input(‘please input the diameter:’); radius=diameter/2;
price=input(‘please input the price:’); area=pi*radius^2;
value=price/area;
disp(value);
Size
Price
Unit value (dollar per square inch)
Small Pizza – 10 inches
6.99
0.0890
Medium Pizza – 12 inches
8.99
0.0795
Large Pizza – 14 inches
10.99
0.0714
Extra Large Pizza – 16 inches
12.99
0.0646
60
30
Homework: Compounded interest
The balance B of a savings account after t years when a principal P is invested at an annual interest rate r and the interest is compounded n times a year is given by:
B = Pæ1+ r önt ç÷
t B = P (1 + r )
ènø t𝑟
Annual B=P(1+r) Monthly 𝐵=𝑃(1+ )’&( (n=1): (n=12): 12
61
Suppose $5,000 is invested for 17 years in one account where the interest is compounded yearly (t=17). In addition, $5,000 is
invested in a second account in which the interest is compounded monthly (n=12, t=17). In both accounts the interest rate is 1.5% (i.e. r=0.015). Use MATLAB to determine (1) the balance of the first account after 17 years, and (2) how long it would take for the second account to reach the same balance.
62
31
P=5000, r=0.015 t1=17
𝐵=𝑃(1+𝑟)!)
Step 1: calculate B
l o g 𝐵𝑃 𝑟 log(1+𝑛)
l o g ‘ 𝐵 + , – ./ 1 𝑡# = (%&”) 𝑃 =+,-()02)
𝑡! = ?
( 1 + 𝑟 ) ” ! * = 𝐵 𝑛 𝑃
𝐵 = 𝑃 ( 1 + 𝑛𝑟 ) ” ! *
𝑛 . 𝑛𝑡# = log(%&’) Step 2: calculate t2 for n=12 ”
𝐵 𝑃
63
Array
qlist elements
qshort-cut expressions qfunctions, e.g. linspace(), zeros() qMore about input/output
64
64
32
Array
qIt is the fundamental unit of data in any MATLAB program.
qAn array is a collection of data values organized into rows and columns, and known by a single name.
qAn individual element within an array can be accessed by including the name of the array followed by subscripts in parentheses that identify the row and column of the element.
3 6 éa(1,1) a(1,2) ù 𝑎= 2 2 êa(2,1) a(2,2)ú
êa(3,1) a(3,2)ú 57êú ëû
65
Arrays
q Single dimensional arrays à vectors § E.g. [1 4 6 7]
qArrays having two or more dimensions § Two-dimensional arrays
§ Multidimentional arrays or matrices
qSize of an array is specified by the number of rows and the number of columns in the array, with the number of rows mentioned first.
§ e.g 3×2
qTotal number of elements in the array will be the product of the number
of rows and number of columns §e.g. 3*2 = 6
66
33
67
a(2,1)=3 b(1,2)=2 c(3,1)=3
Arrays
Store the elements by column-wise in memory.
68
34
MatLab use variables to save arrays
qA single-value variable is considered as an 1×1 array.
>> a=pi a=
3.1416
>> a(1,1)
ans = 3.1416
>> a(2,2)
Index exceeds matrix dimensions.
qA variable can be used to save a array with multiple values § List all the values in brackets ([ ]).
>> a=[1 2] a=
12 >> a=[1 2 3 4]
a=
1234
69
Matrices — arrays with two or more dimensions
q[] – empty matrix.
qUse comma (,) or space to separate elements in
the same row.
qUse semicolon(;) to move to the next row.
qNote: All rows must have the same number of columns.
>> a = [1 2 3; 4 5 6; 7 8 9; 10 11 12] a=
123 456 789
10 11 12
>> a = [1,2,3; 4,5,6; 7,8,9; 10,11,12]
70
35
>> b = [1 2 3; 4 5; 6 7 8; 9 10 11 12]; Error using vertcat
Dimensions of matrices being concatenated are not consistent.
71
Creating arrays
• Arrays can be initialized using
• arithmetic expressions and/or
• all of or portions of previously defined arrays.
e.g. a=[0 1+7] à a=[0 8]
b=[a(2) 7 a]àb=[8 7 0 8] a=[ [1 2] 3]àa=[1 2 3]
72
36
Creating arrays cont..
0 — Default values of array elements.
eg: c(2, 3)=5àc = 0 0 0 005
d=[1,2] ; d(4)=4; à d=[1 2 0 4]
73
Write commands to generate the following arrays
242 a=3 5 b=26 6 4 8 c=4 259
b=[26 6 4 8] a=[2 4;3 5;2 5]
d= e=26 6 4 8 9 d=[] e=[b 9]
c=[2; 4; 9]
74
37
Short cut expressions
qNumbers in a vector may follow a particular pattern
§e.g. a vector from 1 to 100 §e.g. a vector from 10 to 50
qCreate a vector by describing the pattern. §e.g. v=1:100, or v=[1:100]
§e.g v=10:50, or v=[10:50]
qShort cut expressions describe the patterns. §E.g. 1: 100, 10: 50
qGeneral form with default increment 1: start : end
qHow to create a vector v which starts with 4 and ends in 20 with steps of 2?
§v= 4:2:20, or v=[4:2:20]
75
Short cut expressions
Colon (:) operator :
qShort cut notation to create arrays
qGeneral form start: increment : end
eg:x=1:2:10àx=[1 3 5 7 9]
>> x=1:2:13 x=
1 3 5 7 9 11 13 >> x=[1:2:13]
x=
1 3 5 7 9 11 13
76
38
>> y=[1.5:0.1:2.1] y=
1.500 1.600 1.700 1.800 1.900 2.000 2.100
>> z=[-3:7] z=
-3 -2 -1 0 1 2 3 4 5 6 7
>> xa=[21:-3:6] xa =
21 18 15 12 9 6
77
Can you write a short-cut from data?
y=
y=1.5:0.1:2.1 -3 -2 -1 0 1 2 3 4 5 6 7
x=
1 3 5 7 9 11 13
x=1:2:13 1.500 1.600 1.700 1.800 1.900 2.000 2.100
z=
xa =
21 18 15 12 9 6
z=-3:1:7 xa=21:-3:6
78
39
Generate linearly spaced vectors
qHow to create a vector to include 20 numbers from 1 to 20?
qHow to create a vector to include 99 numbers from 1 to 80? § Short cut expression?
ü1: (80-1)/98 : 80
üNeed to figure out the step. Error prone.
qThe linspace() function generates linearly spaced vectors.
§ A linearly spaced vector is a vector with linear (equal) spacing by specifying the first and
last terms, and the number of elements.
§ Similar to short cut expressions, but it gives direct control over the number of points.
§ e.g. y = linspace(a,b) generates a row vector y of 100 points linearly spaced between and
including a and b.
§ e.g. y = linspace(a,b,n) generates a row vector y of n points linearly spaced between and including a and b. For n = 1, linspace returns b.
79
variable_name = linspace(first_value, last_value, n)
xa =
21181512 9 6
>> xa=linspace(21,6,6)
A = linspace(1,5,5);
A = linspace(2,6,3);
A= A= 12345 246
80
40
Use shortcut expressions to generate the following arrays
a=2 4 6 8 b=8 6 4 2 a=2:2:8 b=8:-2:2
81
Use linspace() function to generate the following arrays
a=2 4 6 8 a=linspace(2,8,4)
b=8 6 4 2 b=linspace(8,2,4)
82
41
Accessing Single Element
qUse subscripts (e.g. row number and column number)
>> A = [2 6 9; 4 2 8; 3 5 1] A=
269 428 351
>> A(2,3)
A(2,3) =
8
83
Access single array elements
qThe length of a vector [x1, x2, x3] is 𝑥’& + 𝑥&& + 𝑥”&
qIn MatLab, for a given vector x, its length can be calculated with expression:
sqrt(x(1)^2+x(2)^2+x(3)^2)
veclen.m
Command window
x=input(‘Input coordinates:‘);
length=sqrt(x(1)^2+x(2)^2+x(3)^2);
disp(length);
>>veclen
Input coordinates: [1 2 3]
3.7417
84
42
A=
1 3 5 7 9111315171921
0 5101520253035404550
10 15 20 25 30 35 40 45 50 55 60 67 2 43 68 4 13 1 3 5 3 6
>> A=[1:2:21;0:5:50;linspace(10,60,11);67,2,43,68,4,13,1,3,5,3,6]
85
Initializing arrays with built-in functions
86
43
>> a=zeros(3) a=
000 000 0 0 0
>> a=ones(3) a=
1 1 1 111 111
>> a=eye(3) a=
100 010 001
87
Write commands to generate the following
arrays
100 10000 𝐚= 0 1 0 b= 0 1 0 0 0 001 00100
a=eye(3) b=eye(3,5)
000 111 c= 0 0 0 d= 1 1 1 000 111
c=zeros(3) d=ones(3)
88
44
Input() and DISP()
89
Data input and output
qinput() function qdisp() function
§Only some basic usages in today’s class
qfprintf() function
§ Will introduce later.
90
45
Initializing variables with keyboard input
input()
eg: in1 = input(‘Enter data: ‘); Enter data: 1.23
àstores the value 1.23 into in1
in2 = input(‘Enter a text: ‘, ‘s’);
Enter a text: some text
àstores the character string ‘some text’ into in2
91
More about input() function
>> in1=input(‘Enter data: ‘); Enter data: 1.0+0.23
>> disp(in1)
1.2300
>> in1=input(‘Enter data: ‘); Enter data: sin(pi/2)
>> disp(in1)
1 Enter data: which data?
>> in1=input(‘Enter data: ‘);
Error: Unexpected MATLAB expression.
Enter data:
Any expression that generates numerical values is accepted.
92
46
More about input() function
>> in2=input(‘Enter a text: ‘, ‘s’);
Enter a text: What text?
>> disp(in2);
What text?
>> in2=input(‘Enter data: ‘, ‘s’);
Enter data: ‘1.23’
>> disp(in2);
‘1.23’
>> in2=input(‘Enter data: ‘, ‘s’);
Enter data: 1.0+0.23
>> disp(in2);
1.0+0.23
>> in2=input(‘Enter data: ‘, ‘s’);
Enter data: in1
>> disp(in2);
in1
93
Input()
qRequest user input qSyntax
§ variable_name = input(‘informative text’) variable_name = input(‘ informative text ‘, ‘s’)
Use single quotation marks
qDescription
§Displays the text on the screen and waits for input from the
keyboard
§Returns the values entered and saves it into the variable
üIf ‘s’ is used as the second parameter, input() returns the entered string as a text variable rather than as a variable name or numerical value.
94
47
disp( )
qdisplay text / constants/variables/expressions qSyntax
§ disp(X)
qWhen disp(X) displays a variable, it does not print the variable name.
>> disp(‘PolyU’)
NJIT
>> disp(5) 5
>> disp(pi)
3.1416
>> disp(1.2*0.5+sin(pi/2))
1.6000
>> value=5;
>> disp(value);
5
>> value=5;
>> disp(‘value’);
value
95
Using input() and disp() makes program more user-friendly
Commands to run the script in command window
In cylinder.m
A script without input() and disp()
radius=0.1
cylinder
radius=0.2
cylinder
radius=0.4
cylinder
length=0.5
area=pi*radius^2
volume=area*length
96
48
Using input() and disp() makes program more user- friendly
In cylinder.m
Radius=input(‘Radius is’)
length=0.5
area=pi*radius^2
volume=area*length
disp(‘volume is’);
disp(volume);
Commands to run the script in command window
>>cylinder
Radius is 0.1
Volume is 0.0157
>>cyclinder
Radius is 0.2
Volume is 0.0628
…
97
Use disp() to display arrays and strings
>> disp(1:3); >> disp(1:2:7); 123 1357
>> disp(linspace(1,7,4)); 1357
98
49
Text strings
qA MATLAB string is an array of character. ′h′ ′𝑖′ ′′ ′𝑡! ′h! ′𝑒! ′𝑟′ ′𝑒′
>> a =’hi there’ a=
hi there
>> a(1)
ans =
h
>> a(2)
ans =
i
>> a(3) ans =
>> a = [‘john’ ; ‘kate’ ; ‘anna’ ]
a= 𝑗𝑜h𝑛 john 𝑘𝑎𝑡𝑒 kate 𝑎𝑛𝑛𝑎 anna
>> a(4)
ans = ta=
>> a=’pi’ a=
pi
′𝑝′ ′𝑖′
>> a=[‘p’ ‘i’] x pi
[3.1415926]
99
Text strings
An array can be initialized with all or part of elements in another array. So does a text string.
>> a=[‘hi’ ‘ ‘ ‘there’]
123
a=
hi there
Concatenate strings:
new_string = [string1 string2 … string_n]
100
50
Use disp() to display arrays and strings
>> a=‘COMP2022′; >> disp(a);
COMP2022
>> disp([‘hi’ ‘ ‘ ‘there’]);
hi there
>> disp([1 2 3]);
123
101
Example: Greeting the user
Write a small program (greeting.m) to accept the name of the user (person who runs the program) and then greet the user.
For example, if the user provides a name Tom, the program should print out Hi Tom!.
Name=input(‘please provide your name’, ‘s’); disp([‘Hi ‘ Name ‘!’]);
102
51
Input(): accept user’s array input
qInput() accepts a single value, e.g. § r = input(‘Please provide a radius:’);
qCan input() accept multiple values and save them into an array?
>> a = input(‘Please provide some values:’) Please provide some values:1 2 3
123 |
Error: Unexpected MATLAB expression.
>> a = input(‘Please provide some values:’) Please provide some values:[1 2 3]
a=
123
103
An example: sum the elements in an array
qThe example shows how to input an array, use its elements in expressions, and display the elements.
1. Create the following script and save it into sum4ele.m. The script only works for arrays with 4 elements.
2. Run the script in command window.
In editor window
In command window
a= input(‘Please input a 4-element array:’);
sum=a(1)+a(2)+a(3)+a(4);
disp(‘The array is’);
disp(a);
disp([‘The sum is ‘ num2str(sum)]);
>> sum4ele
Please input a 4-element array:[1 2 3 4]
The array is
1234 The sum is 10
104
52
num2str()
qA built-in MatLab function
qCreate a string based on the value of a numerical expression
>> mystr=num2str(2*3.0^2)
mystr =
18
>> mystr(1)
ans =
1
>> mystr(2)
ans =
8
105
PUT TOGETHER
106
53
Ex: Similarity between two points
The similarity between two points in a 3-D space can be measured by the distances between them. The smaller the distance is, the more similar they are. There are three types of distances, which can be calculated with the x,y,z coordinates for the points.
Given two points (x1,y1,z1) and (x2, y2, z2): qManhattan (L1) distance:
qEuclidean (L2) distance: qCosine distance:
107
Write a script to calculate the three distances
qUse an input() function to get the x coordinates as an array from keyboard and save them into variable x
§ x(1) is the x coordinate of point #1, and x(2) is the x coordinate of point #2 qUse input() functions to get the y coordinates and z coordinates in a
similar way and save them into variable y and z, respectively. qCalculate the distances and save them into an array d
§ d(1) is Manhattan (L1) distance, d(2) is Euclidean (L2) distance, and d(3) is Cosine distance
§ You may use the following built-in math functions: üabs(x) — returns the absolute value of x
üsqrt(x) — returns the square root of x
qUse disp() function to display the distances. qSave script into distances.m.
108
54
x=input(‘Please input two x coordinates in an array’);
y= …
z= …
d(1)=abs(x(1)-x(2))+ … ;
d(2)= …
d(3)= …
disp([‘Manhattan distance:’
disp([‘Euclidean (L2) distance:’ … ]);
disp([‘Cosine distance:’ … );
num2str(d(1))]);
109
55