程序代写代做 AI C html algorithm flex COMP2022 Programming for FinTech Applications

COMP2022 Programming for FinTech Applications
Spring 2020
Professor: Dr. Grace Wang April 24 2020 Friday
1
1
Agenda
qReview R Quiz
qMatlab: Array and Matrix qMatlab: Programming structure
2
2
1

Quiz R
qAverage: 10.3/20
qHighest: 19/20
§Lee Cheuk Yin. Very impressive work.
3
3
Matlab
qMatlab: originally from “Matrix Laboratory” §Can handle arrays/matrices very efficiently
qTo learn Matlab well: § Matrices
§General programming structure §Functions, libraries, and tools
4
4
2

Sub-array
6
How to access multiple elements?
qE.g. change the values in a big array
1111111111 01
00
00
00 0000011111 0000111111 0001111111 0011111111 0111111111
§ Add 1 to each of the element on the first row.
§ Substrate 1 from each element on rows 2 to 5 and columns 3 to 9.
qchange each individual element — tedious quse loops (will introduce later) — inconvenient qUse subarray
11111111 11111111 01111111 00111111
7
3

Sub-array
qEach subscript can be an array § Select all the rows/columns(:)
§ The last row/column (end)
qUsing subarrays on the lef-hand side of an assignment statement qAssigning a scalar to a subarray
8
arr1=[1.1 -2.2 3.3 -4.4 5.5]
>> arr1(3) ans =
3.3000
1.1000 -4.4000 1.1000 3.3000 5.5000
>> arr1(1:2:5) ans =
>> arr1([1 4]) ans =
9
4

Colon (:) by itself refers to all the elements in a row or column.
arr2=[1,2,3;-2,-3,-4;3,4,5]
: cannot be omitted.
arr2 = 123
-2 -3 -4 345
>> arr2(:,1:2:3) ans =
13 -2 -4 35
>> arr2(1,:) ans =
123 >> arr2(1,)
arr2(1,) |
Error: Unbalanced or unexpected parenthesis or bracket.
10
The keyword end refers to the last row or column
eg:arr3=[8 7 6 5 4 3 2 1] arr3(end)à1
arr3(5:end)à[4 3 2 1];
Value returned by end is always the highest value of a given subscript.
11
5

arr4=[1,2,3,4;5,6,7,8;9,10,11,12]
arr4 = 1234 5678 9 101112
>> arr4(2:end,2:end) ans =
678 10 11 12
12
arr4=[1,2,3,4;5,6,7,8;9,10,11,12]
arr4 = 1234 5678 9 101112
>> arr4(1:2,[1 4])=[20,21;22,23] arr4 =
20 2 3 21 22 6 7 23 9 10 11 12
13
6

arr4=[1,2,3,4;5,6,7,8;9,10,11,12]
arr4 = 1234 5678 9 101112
arr4(1:2,1:2)=1 àarr4=1 1 3 4
1178 9 101112
14
Exercise
>> c(2,:) ans =
0.6000 1.1000 -0.6000 3.1000
1.1 -3.2 3.4 0.6 éù
c = ê0.6 1.1 -0.6 3.1ú êú
ê1.3 0.6 5.5 0.0ú ëû
15
7

Exercise
>> c(:,end) ans =
0.6000 3.1000 0
1.1 -3.2 3.4 0.6 éù
c = ê0.6 1.1 -0.6 3.1ú êú
ê1.3 0.6 5.5 0.0ú ëû
>> c(1:2,2:end) ans =
-3.2000 3.4000 0.6000 1.1000 -0.6000 3.1000
16
Exercise
1.1 -3.2 3.4 0.6 éù
c = ê0.6 1.1 -0.6 3.1ú êú
>> c(6) ans =
0.6000
>> c(4:end)
ans =
-3.2 1.1 0.6 3.4 -0.6 5.5 0.6 3.1 0
ê1.3 0.6 5.5 0.0ú ëû
17
8

>> c([1 3],2) ans =
-3.2000 0.6000
>> c([2 2],[3 3]) ans =
-0.6000 -0.6000 -0.6000 -0.6000
1.1 -3.2 3.4 0.6 éù
c = ê0.6 1.1 -0.6 3.1ú êú
ê1.3 0.6 5.5 0.0ú ëû
>> c(1:2,2:4) ans =
-3.2000 3.4000 0.6000 1.1000 -0.6000 3.1000
18
a= 123
456 789
>> a([1 3],:)=a([2 2],:)
a= a=
456 456 456 456 456
>> a([3 1],:)=a([1 3],:) a=
789 456 123
>> a=a([2 2],:)
19
9

>> a=eye(3,3) a=
100 010 001
>> b=[1,2,3];
>> a(2,:)=b a=
100 123 001
20
>> a=eye(3,3) a=
100 010 001
>> b=[4,5,6];
>> a(:,3)=b’ a=
104 015 006
21
10

>> a=eye(3,3) a=
100 010 001
>> b=[7,8,9];
>> a(3,:)=b([3 1 2]) a=
100 010 978
22
Subarray
» A=[2,3,4;5,6,7;8,9,0] A=
90
Select the second row
» c=A(2,:) c=
567
Select the first column
2
5
8
34
» b=A(:,1) b=
2 5 8
Select a block
» d=A(1:2,2:3) d=
34 67
67
23
11

0.0 2.1 6.0 0.0 −6.6 3.4 2.1 0.3 1.3 1.1 0.0 −2.0
4×5
6.0 1.3
24
Write commands to carry out the operations below
qcreate a row vector x of 5 equally spaced elements between 2 and 3 (hint: use linspace function)
>> x=linspace(2,3,5)
% linspace(X1, X2, N) generates N points between X1 and
X2.
qincrease the second element by 1
>> x(2)=x(2)+1
qcreate a second row vector y of same size as x, with elements equal to the successive even integers starting with 4.
>> y=4:2:12
qcreate an array A, whose first row is equal to x, whose second row is a line of ones, and whose third row is equal to y.
>> A=[x; ones(1,5); y]
25
12

Write commands to carry out the operations below
qdefine a row vector z, whose elements are equal to the second row of A.
z=A(2,:);
qSet all the elements on the second column of A to 0.
A(:,2)=0;
qdefine an array B to include all the values in A whose row numbers and column numbers are both odd.
B=A(1:2:3,1:2:5);
qSwap the first column and the last column of A. A(:,[5 1])=A(:,[1 5]);
26
Disp() and fprintf()
27
13

disp() function
qdisp() is a function that will display the value or values in a variable
>> name = ‘Jim’;
>> disp(name);
>> a=[0 1; 2 3];
>> disp(a);
qAlready introduced in the class, refer to lecture notes for details
28
Instead of using disp(), we can use fprintf ()
qMore flexible way to display data
qDisplays one or more values together with related text and let the
programmer control the way that the displayed value appears.
qAn example:
>>fprintf(‘The value of pi is %f \n’, pi);
The value of pi is 3.141593
The characters %f are conversion characters; they indicate that a value in the data list should be printed out in floating-point format (real number) at that location in the format string.
\n are called escape characters, indicating the line feed; text starts on the next line.
29
14

General form of fprintf()
qfprintf(format_string, values)
§ Eg: fprintf(‘The value of pi is %f \n’, pi);
qFormat_string:
§ A text string (use single quotation marks)
§ In the string, there are conversion characters (e.g. %f)
§ Conversion characters are place-holders for the values to be printed and will be replaced by the corresponding values
qValues
§ Different values are separated by comma ( , ) § Maybe numbers, constants, and expressions
30
qCommon conversion characters used in format string
Display value as an integer (digital number) Display value in scientific format
Display value in floating-point format Display value as a string
§ %d
§ %e
§ %f
§ %s
§ https://www.mathworks.com/help/matlab/matlab_prog/formatting-strings.html
>> fprintf(‘Sum of %d and %d is %d\n’, 1, 3, 4); Thesumof1and3is4
Scientific format (%e)
>> fprintf(‘The The value of pi
>> fprintf(‘The The value of pi
>> fprintf(‘The The value of pi
>> fprintf(‘The The value of
pi is 3.1416>>
value of pi is %e\n’, pi); is 3.141593e+00
value of pi is %f\n’, pi); is 3.141593
Convert a number to a string then display the string (%s)
value of pi is %s\n’, num2str(pi)); is 3.1416
value of\n pi is %s’, num2str(pi));
MATLAB does not change the line when \n is missing
31
15

The %f conversion character can include numbers in between the % and f to control the number of spaces and decimal places.
>> fprintf(‘The value of pi is %11.9f\n’, pi); The value of pi is 3.141592654
The 11 in this example instructs MATLAB to use 11 total spaces (includes decimal point and decimal places) and show 9 digits after the decimal point.
>> fprintf(‘Time to reach the amount: %7.3f years\n’, t2); Time to reach the amount: 16.884 years
>> fprintf(‘Time to reach the amount: %15.2f years\n’, t2); Time to reach the amount: 16.88 years
>> fprintf(‘Time to reach the amount: %5.2f years\n’, t2); Time to reach the amount: 16.88 years
32
%g: same format as %f or %e, depending on the value.
• Scientific notation is used only if the exponent is greater than 5 or less than -4.
• Trailing zeros are removed
>> fprintf(‘%e\n’,312.4*100);
3.124000e+04
>> fprintf(‘%f\n’,312.4*100);
31240.000000
>> fprintf(‘%g\n’,312.4*100);
31240
>> fprintf(‘%e\n’,312.4*10000);
3.124000e+06
>> fprintf(‘%f\n’,312.4*10000);
3124000.000000
>> fprintf(‘%g\n’,312.4*10000);
3.124e+06
33
16

Swapping data
%initialization >> a=1
>> b=2 %swapping
>> c=a
>> a=b >> b=c
%initialization
>> a=1
>> b=2
%swapping?
>> a=b >> b=a
%initialization
>> a=eye(3)
%swapping columns
%1 and 3
>> b=a(:,1)
>> a(:,1)=a(:,3)
>> a(:,3)=b
%initialization
>> a=eye(3)
%swapping columns
%1 and 3
>> a(:,1)=a(:,3)
>> a(:,3)=a(:,1)
%initialization
>> a=eye(3)
%swapping columns %1 and 3
>> a(:,[3 1])=a(:,[1 3])
34
Continue Long Statements on Multiple Lines
qIf your expression does not fit on one line, use an ellipsis (three or more periods at the end of the line) and continue on the next line.
>>c = 1+2+3+ …
5+6+7;
35
17

Multidimensional Arrays
qAn array having more than two dimensions is called a multidimensional array in the MATLAB.
qMultidimensional arrays in MATLAB are an extension of the normal two-dimensional arrays.
§Two-dimensional arrays use two subscripts (row, column) for indexing
§Multidimensional arrays use additional subscripts for indexing.
§E.g. A three-dimensional array uses three subscripts: ürow, column, page
36
37
18

Manipulating Multidimensional Arrays
>> A = [1 0 3; 4 -1 2; 8 2 1]
A = 103
4 -1 2 821
>> A(:,:,2) = [6 8 3; 4 3 6; 5 9 2] A(:,:,1) =
103 4 -1 2 821
A(:,:,2) =
683 436 592
>> size(A)
ans = 332
38
Manipulating Multidimensional Arrays
qExtending two-dimensional array into three-dimensional array
qExtending three-dimensional array into four-dimensional array
39
19

>> a=[1,2;3,4];
>> size(a)
ans =2 2
http://en.wikipedia.org/wiki/Hypercube
>> b=a;
>> a(:,:,2)=b;
>> size(a)
ans =2 2 2
>> b=a;
>> a(:,:,:,2)=b;
>> size(a)
ans=2 2 2 2
>> b=a;
>> a(:,:,:,:,2)=b;
>> size(a)
ans=2 2 2 2 2
40
Array Operations
qOperation performed between arrays based on an element-by element basis or operation performed between an array and a scalar
q𝐴=12 B=56 34 78
qA+B=1+52+6=6 8 3+7 4+8 10 12
qA+4=1+4 2+4=5 6 3+44+478
41
20

Transpose ( ‘ ) operator :
qSwaps the row and columns of any array that it is applied to. qUseful to initialize column vectors and more complex
arrays.
eg: f=[1:4]’àf= 1 , g=1:4; h=[g’ g’]àh= 1 1 222 333 444
42
43
21

Array operations
𝐴=12 B=56 34 78
A+B=6 8
1012 A.*B= 5 12 A*5=A.*5= 5 10
B-A=4 4
44 56
B-2=3 4 A./B= 1/5 2/6 = 0.2 0.3333
21 32
3/7 4/8 0.4286 0.5000
15 20
A.\B=5/16/2= 5 3 7/3 8/4 2.333 2
No .+ or .- operator!
A.+B
Error: unexpected MATLAB operator.
44
qCreatethreearrays:A= 1 2 𝐵= 4 −2 𝐶= 1 4−1 −63 2
qWith MatLab, evaluate the following expressions §Array operations
A+B A.*2 A+1 A./B A-B A.\B A-1 A./2 A.*B A.\2
A.^2 A.^B
45
22

qCreatethreearrays:A= 1 2 𝐵= 4 −2 𝐶= 1 4−1 −63 2
qWith MatLab, evaluate the following expressions §Illegal operations
A.+B A.-B
A+C A.*C A-C A./C
Why they are illegal?
46
qCreatethreearrays:A= 1 2 𝐵= 4 −2 𝐶= 1 4−1 −63 2
qWith MatLab, evaluate the following expressions § Matrix operations vs. array operations
A*B compare the result against A.*B
A*C compare the result against A.*C
A^2 compare the result against A.^2
Wonder why the are different?
47
23

Built-in array functions
qMATLAB has build-in functions operating arrays § E.g. max(), min(), sum(), …
>> a=1:5
a =1 2 3 4 5
>> min(a)
ans = 1
>> max(a)
ans = 5
>> [max_value, max_pos]=max(a)
max_value = 5
max_pos = 5
48
Built-in array functions
49
24

50
51
25

52
Using arrays as input parameters
>> a=0:pi/4:2*pi;
>> b=sin(a);
>> disp(b)
0 0.7071 1.0000 0.7071 0.0000 -0.7071 – 1.0000 -0.7071 -0.0000
b=sin(a)
b(1)=sin(a(1)) b(2) = sin(a(2)) b(3)=sin(a(3)) …
53
26

Matrix, array operations and matrix operations
54
Matrix
qMatLab —- matrix laboratory
qA 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
55
27

Special matrices
Zero matrix: A matrix all of whose entries are zero é0 0 0 0ù
ê0 0 0 0ú zeros() ê0 0 0 0ú
ëû
Identity matrix: A square matrix which has ‘1’ s on the diagonal and zeros everywhere else.
é1 0 0ù ê0 1 0ú
ê0 0 1ú ëû
eye()
56
Array operations
𝐴=12 B=56 34 78
A+B=6 8
1012 A.*B= 5 12 A*5=A.*5= 5 10
B-A=4 4
44 56
B-2=3 4 A./B= 1/5 2/6 = 0.2 0.3333
21 32
3/7 4/8 0.4286 0.5000
15 20
A.\B=5/16/2= 5 3 7/3 8/4 2.333 2
No .+ or .- operator!
A.+B
Error: unexpected MATLAB operator.
57
28

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
Addition of two matrices
58
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
Matrix Subtraction
59
29

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.
Multiplication by a scalar
60
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
mxr
inside
rxn mxn
Matrix multiplication
61
30

Matrix operations
If a and b are two vectors of the same size
éa1ù éb1ù êú êú
>> a=[1 2 3]; b=[4 5 6];
>> dot(a,b) a = ê a 2 ú ; b = ê b 2 ú a n s =3 2
Scalar (dot) product of two vectors
ê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) =
62
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ú ëû
Matrix multiplication
-1 -3 1
63
31

Matrix Multiplication Another example:
é21ùé5ùé8ù
ê-9 0ú•ê ú=ê-45ú ê úë-2ûêú
ê10 -5ú ê60ú ëûëû
3×2 2×1 3×1
64
dot(a,b) =C𝑎 ∗ 𝑏! if a, b are row vector 𝑎!∗𝑏 ifa,barecolumnvectors
>> a=[1 2 3];
>> b=[4 5 6];
>> dot(a,b)
ans =
32
>> a*b’ ans =
32 >> a’*b
ans = 456
8 10 12 12 15 18
>> a=[1;2;3];
>> b=[4;5;6];
>> dot(a,b)
ans =
32 >> a’*b
ans = 32
>> a*b’ ans =
456
8 10 12 12 15 18
65
32

Matrix operations
Properties of matrix multiplication:
1. Matrix multiplication is noncommutative
(order of addition does matter) AB 1 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
Properties
66
Array Multiplication vs. Matrix Multiplication
For the multiplication of A and B
qSizes
§ Array multiplication: A and B should have the same size
§ Matrix Multiplication: number of columns of A = number of rows of B
qOperators:
§ 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.
67
33

Matrix operations
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
Multiplication of matrices
Properties
68
Inverse matrix and matrix division
qWhen you multiply a matrix and its inverse, you get the identity matrix.
3 −1 × 2 1 = 1 0 −5 2 5 3 0 1
qinv() function
§ The inverse matrix of A : A-1=inv(A)
qMatrix right division A/B is defined as A*B^-1, or A*inv(B).
qMatrix left division A\B is defined as A^-1*B, or inv(A) * B.
§ It is not B/A. B/A = B*A-1.
69
34

Array right division and array left division
A./B= 1/5 2/6 = 0.2 0.3333 3/7 4/8 0.4286 0.5000
A.\B= 5/1 6/2 = 7/3 8/4
53 2.333 2
70
Example #1: A Telling Example
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.
é-2 3ùéxù=é5ù êë – 4 1 úû êë y úû êë 8 úû
ì-2x+3y = 5 íî-4x+y = 8
71
35

Example #2: Another Telling Example
Use your observations from the previous example to find matrices A, X, and B such
AX = B
the system of ì x – y + z = 8
that the matrix equation
is equivalent to
linearequations ïí2x+3y-z = -2
ï3x-2y-9z = 9 î
72
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ú ëû
73
36

Consider the equation ax = b.
How would you solve this equation for x?
Perhaps, you would divide both sides by a and obtain
x = ba
74
Here is another way to solve ax = b :
Multiply both sides of the equation by
the multiplicative inverse of a, i.e.
1a .
ax=bÛ 1ax=1b aa
a a x = ba
1.x =
Hence, we conclude that
b
a
x = ba .
75
37

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
76
Remember:
-1 X=AB
Since order matters in
matrix multiplication, -1 do not write X = BA
77
38

Example #2
Solvethesystem ì 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ú ëûëûëû
78
X = A-1B.
How to calculate X with MATLAB?
or
X=inv(A)*B
é4ù
êú X = -3
ê 1 ú ëû
X=A\B
We conclude that
x = 4, y = -3, and z = 1.
>> X=B/A
??? Error using ==> mrdivide Matrix dimensions must agree.
79
39

80
Example #4
ì5x-x-x =0 Solve the system ï123
A=ê1 1 0ú,X=x2,andB=5
í x1+x2 = 5 ï2x-3x =2
î13
éxù é0ù
é5 -1 -1ù êúê1úêú
ê2 0 -3ú êx ú ê ú ë ûë3û ê2ú ëû
81
40

or
é 0.8125 ù
X =ê4.1875ú
ê- 0.125ú ëû
X=inv(A)*B
X=A\B
We conclude that x1 = 0.8125,
x2 = 4.1875 x3 = -0.125
82
83
41

AX = B
Step 1: create and initialize matrix A and column vector B.
84
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
85
42

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
86
Common mistakes when writing expressions
qMissing *
§2x 2●x 2*x
§ 2sin(x) 2●sin(x)
qMissing parentheses § sin x
§ log 10
qe is not a constant
§ e^2
2*sin(x)
sin(x) log(10)
exp(x)
qFunction name, parentheses, parameters cannot be separated
§ sin^-1(x) sin(x)^-1
qWrite expression using subscripts / superscripts § Second element in an array A
üA2 A(2)
87
43

Common mistakes when writing expressions
qParentheses, brackets, and curly brackets (or braces) § To change precedence, use parentheses
ü[ (a + b) * c + d] * e ( (a + b) * c + d ) * e ü{ [ (a + b) * c + d] * e + f} * g
( ( (a + b) * c + d ) * e + f ) * g
§ To create arrays, use brackets. E.g.
üA={1 2 3 4} A=[1 2 3 4]
§ To get element(s) in an array, use parentheses üA[1]=1; A(1)=1
88
Logical data type
q Special type of data that can have one of only two possible values: true or false.
§ MATLAB uses 1 to represent true and 0 to represent false § MATLAB takes zero as false and non-zeros as true
q Relational operations
§ Test some kind of relation between two entities (numerical data or
character strings)
§ E.g. if one number is greater than the other
q Logical operations operate logical data
89
44

Relational operations
90
Logical operations
91
45

Logical operations
92
TABLE
qAge = [38;43;38;40;49]; Smoker = logical([1;0;1;0;1]); Height = [71;69;64;67;64]; Weight = [176;163;131;133;119]; BloodPressure = [124 93; 109 77; 125 83; 117 75; 122 80]; T = table(Age,Smoker,Height,Weight,BloodPressure)
93
93
46

Branching Statements
94
Outline
qBranch statements allow you to select and execute specified sections of code (called blocks) while skipping other sections of code
§If construct
üif … elseif …else … end
§Switch construct üswitch … case … end
§try/catch construct ütry… catch… end
95
47

If construct —- the simplest form
Example:
x=input(‘please input a number’);
true
if x>0
disp(‘Your input is a positive number’);
end
x>0?
false
disp(‘Your input is a pos….
96
If construct — the if/else structure
Example:
x=input(‘Please input a number’);
true x>0 false
if x>0
disp(‘Your input is a positive number’);
else
disp(‘Your input is zero or negative’) end
disp(‘… positive…’);
disp(‘… zero or negative…’);
97
48

If construct : if – elseif -else structure
Example:
x=input(‘Please input a number’); if x>0
disp(‘Your input is a positive number’); elseif x<0 disp(‘Your input is negative’); else disp(‘Your input is zero’); end false x>0? true true
disp(‘ … positive…’);
false
x<0? disp(‘...zero’); disp(‘... negative’); 98 if construct --- general form if control_expression 1 statements elseif control_expression 2 statements elseif control_expression 3 statements else Each statement block can be • Empty,or • 1statement,or • Multiplestatements,or • Aconstruct,e.g.anif construct §control_expressions are logical expressions that control the operations in the if construct §There can be any number of elseif clause (0 or more), but there can be at most one else clause statements end 99 49 Ex. Pounds to kilograms (pd2kg) Write a program(pd2kg.m) to convert a weight expressed in pounds into kilograms. Input: the weight in pounds. Output: the weight in kilograms Method: Kilograms = Pounds / 2.2 Since a weight cannot be a negative number, the program should not accept a negative number as a valid weight. It should print an error message if the weight entered in pounds is negative. 100 Pseudo code Accept a number (i.e. weight in pounds) Check the number. If the number is negative If construct Display an error message Branch 1: disp(...) Otherwise else convert pounds into kilograms calculation Call input function display the weight in kilograms disp(...) Branch 2 pounds=input('Please input the weight in pounds:'); if pounds<0 disp('Invalid weight.'); else kilograms=pounds/2.2; fprintf('It is %f kilograms.\n', kilograms); end 101 50 pd2kg.m Command window pounds=input('Please input the weight in pounds:'); if pounds<0 disp('Invalid weight.'); else kilograms=pounds/2.2; fprintf('It is %f kilograms.\n', kilograms); end >> pd2kg
Please input the weight in pounds:-10
Invalid weight.
>> pd2kg
Please input the weight in pounds:0
It is 0.000000 kilograms.
>> pd2kg
Please input the weight in pounds:100
It is 45.454545 kilograms.
102
Ex: Check user input
Write a program (checkinput.m) to
1. prompt the user for a number ( use input() )
2. if the number is smaller than 5, or between 8 & 10, or greater than 33 (what is the expression in if statement? How to describe the condition “between 8 and 10”? How many conditions (4)? How to combine the conditions? )
print good —– disp(‘good’)
3. Otherwise
printbad—– disp(‘bad’)
Hint: Use the | operator in your if statement. (Where is | on keyboard?)
103
51

checkinput.m
Which numbers should be used as inputs to test the program?
Rules:
The inputs that can test all the conditions.
The inputs that can cover all the branches.
num = input(‘Please provide a number:’);
if num<5|(num>=8&num<=10)|num>33
disp(‘good’);
else
disp(‘bad’);
end
104
checkinput.m
num = input(‘Please provide a number:’);
if num<5|(num>=8&num<=10)|num>33
disp(‘good’);
else
disp(‘bad’);
end
Command window
Command window
>> checkinput
Please provide a number:11
bad
>> checkinput
Please provide a number:50
good
>> checkinput
Please provide a number:1
good
>> checkinput
Please provide a number:6
bad
>> checkinput
Please provide a number:8
good
105
52

x = input (‘Please enter x ‘);
y = input (‘Please enter y ‘);
if x>=0 & y>=0
f=x+y;
elseif x>=0 & y<0 f=x+y^2; elseif x<0 & y>=0
f=x^2+y;
else
f=x^2+y^2;
end
fprintf(‘f is %f\n’, f);
106
if construct — general form
if control_expression 1
statements
elseif control_expression 2 statements
elseif control_expression 3 statements
else
statements
end
Each statement block can be
• Empty,or
• 1statement,or
• Multiplestatements,or • Aconstruct,e.g.anif
construct
§control_expressions are logical expressions that control the operations in the if construct
§There can be any number of elseif clause (0 or more), but there can be at most one else clause
107
53

Nested if constructs
qif constructs may be nested. Two if constructs are said to nested if one of them lies entirely within a single code block of the other one.
if control_expression 1
if control_expression 2

end end
108
Example: Signum function
qY = sign(X) returns an array Y the same size as X, where each element of Y is:
§ 1 if the corresponding element of X is greater than zero § 0 if the corresponding element of X equals zero
§ -1 if the corresponding element of X is less than zero
Pseudo code:
xßInput()
If x is greater than 0, then yß1
Otherwise (i.e. x is equal to zero, or x is less than zero)
if x is equal to zero yß0
otherwise (i.e. x is less than zero, but no need to check)
yß -1 end
End
Show the value of y
if x>0 y=1;
else
if x==0 y=0;
else y=-1;
end
end
109
54

elseif and embeded if construct
if x>0 y=1;
y=0; else
y=-1; Remove end
if x>0 y=1;
else
if x==0
end
y=0; else
y=-1;
end
elseif x==0
110
x = input (‘Please enter x ‘); y = input (‘Please enter y ‘); if x>=0 & y>=0
f=x+y; elseif x>=0 & y<0 f=x+y^2; elseif x<0 & y>=0
f=x^2+y;
else
f=x^2+y^2;
end
fprintf(‘f is %f\n’, f);
111
55

x = input (‘Please enter x ‘);
y = input (‘Please enter y ‘);
if x>=0 & y>=0 elsef=x+y;
if x>=0 & y<0 f=x+y^2; else if x<0 & y>=0 f=x^2+y;
else endf=x^2+y^2;
end
end
%level 1, if
%level 1, else
%level 2, if
%level 2, else
%level 3, if
%level 3, else
%level 3, end
%level 2, end
%level 1, end
fprintf(‘f is %f\n’, f);
112
Ex. Pounds to kilograms (pd2kg)
Write a program(pd2kg.m) to convert a weight expressed in pounds into kilograms.
Input: the weight in pounds. Output: the weight in kilograms Method: Kilograms = Pounds / 2.2
Since a weight cannot be a negative number, the program should not accept a negative number as a valid weight. It should print an error message if the weight entered in pounds is negative.
113
56

pd2kg.m
Command window
pounds=input(‘Please input the weight in pounds:’); if pounds<0 disp('Invalid weight.'); else kilograms=pounds/2.2; fprintf('It is %f kilograms.\n', kilograms); end >> pd2kg
Please input the weight in pounds:-10
Invalid weight.
>> pd2kg
Please input the weight in pounds:0
It is 0.000000 kilograms.
>> pd2kg
Please input the weight in pounds:100
It is 45.454545 kilograms.
114
pd2kg.m
pounds=input(‘Please input the weight in pounds:’); if pounds<0 disp('Invalid weight.'); else kilograms=pounds/2.2; if kilograms <= 1 fprintf('It is %f kilogram.\n', kilograms); else fprintf('It is %f kilograms.\n', kilograms); end end 115 57 pd2kg.m pounds=input('Please input the weight in pounds:'); kilograms=pounds/2.2; if pounds<0 disp('Invalid weight.'); elseif kilograms <= 1 fprintf('It is %f kilogram.\n', kilograms); else fprintf('It is %f kilograms.\n', kilograms); end 116 Energy to Decibel The energy produced by vibrations is known as sound. The sound energy density level gives the ratio of a sound incidence as a sound energy value in comparison to a reference level of 0 dB (DIN 45630). It is a logarithmic measure of the ratio of two sound energy densities. 𝐷 = 1 0 ∗ 𝑙 𝑜 𝑔 𝐸𝐸 " 𝐸 =10#$% & " '! 117 58 decibel.m energy=input('Please input the energy:'); if energy<=0 disp('Invalid energy.'); else decibel=10*log10(energy/10^-12); if decibel<= 1 fprintf('It is %f dB.\n', decibel); else fprintf('It is %f dBs.\n', decibel); end end 118 Ex. Body Mass Index (BMI) BMI is a measure of obesity for adult men and women. The BMI is calculated by dividing the body weight (in kilograms) by the height (in meters) squared. 𝐵𝑀𝐼 = 𝑤𝑒𝑖𝑔h𝑡 h𝑒𝑖𝑔h𝑡 ! Write a program (mybmi.m) that (1) accepts the body weight (in kilograms) and the height (in meters) of a person, (2) calculates the Body Mass Index (BMI) of the person based on the inputs, and (3) print out if the person is under-weight, normal weight, overweight, obese, or morbidly obese. If BMI... BMI<18.5 18.5≤BMI<25 25≤BMI<30 30≤BMI<40 BMI≥40 The person is... Underweight Normal weight Overweight Obese Morbidly obese 119 59 height = input(...) weight= input(...) bmi = ... if ... disp(‘underweight’); elseif ... disp(‘Normal weight’); elseif ... disp(‘Overweight’); elseif ... disp(‘Obese’); else disp(...); end 1. Input height 2. Input weight 3. Calculate BMI = weight/height^2 4. An if construct with 5 branches depending on BMI If BMI... BMI<18.5 18.5≤BMI<25 25≤BMI<30 Overweight 30≤BMI<40 Obese BMI≥40 Morbidly obese The person is... Underweight Normal weight 120 weight=input('input weight in kg: '); height=input('input height in m: '); bmi = weight/height^2; fprintf('bmi is %7.2f.\n', bmi); if bmi<18.5 disp('Underweight'); elseif bmi>=18.5 & bmi<25 disp('Normal weight'); elseif bmi>=25 & bmi<30 disp('Overweight'); elseif bmi>=30 & bmi<40 disp('Obese'); else disp('Morbidly obese') end weight=input('input weight in kg: '); height=input('input height in m: '); bmi = weight/height^2; fprintf('bmi is %7.2f.\n', bmi); if bmi<18.5 disp('Underweight'); elseif bmi<25 %bmi must be >=18.5 here
disp(‘Normal weight’); elseifbmi<30 %bmimustbe>=25here
disp(‘Overweight’);
;elseif bmi<40 %bmi must be >=30 here
disp(‘Obese’);
else %bmi must be >=40 here
disp(‘Morbidly obese’);
end
How to test the program —- Weights and heights that can generate BMIs in different ranges.
121
60

The switch construct
The switch construct is another form of branching construct. It permits a programmer to select a particular set of statement to execute based on a value (e.g. a constant, a number, a string, an expression, …).
General Form
switch parameter or control expression case possible values
end

branch 1
case possible values branch 2
There is no limit
. to the number
.
. otherwise
of cases.
122
Real-life examples
pay cash case ez_pass
ez_pass is charged case exact_change
put coins end
switch payment_method case cash
123
61

switch statement
qAllows for evaluation of multiple cases of the same parameter
qThe switch statement is looking for the parameter to have an exact match to one of the cases. (No a= 6;
surcharge = inf;
end
Change the
if construct into a switch construct
if surcharge ~= inf
fprintf(‘Premium is %d.\n’, premium+surcharge);
else
fprintf(‘No insurance.\n’);
end
128
age=input(‘Please provide an age:’); accidents=input(‘Number of accidents:’); premium=500; surcharge=0;
if age<25 surcharge = 100; end switch accidents case 1 surcharge=surcharge+50; case 2 surcharge=surcharge+125; case 3 surcharge=surcharge+225; case 4 surcharge=surcharge+375; case 5 Change the otherwise if construct if surcharge~= inf fprintf('Premium is %d.\n', premium+surcharge); else fprintf('No insurance.\n'); end surcharge=surcharge+575; end otherwise surcharge = inf; end switch construct switch surcharge case inf fprintf('No insurance.\n'); into a fprintf('Premium is %d.\n', ... premium+surcharge); 129 64 Example 130 day = input('Enter name of day: ','s'); day = upper(day); switch day case 'SUNDAY' day_no = 1; case 'MONDAY' day_no = 2; case 'TUESDAY' day_no = 3; case 'WEDNESDAY' day_no = 4; case 'THURSDAY' day_no = 5; case 'FRIDAY' day_no = 6; case 'SATURDAY' day_no = 7; otherwise day = input('Enter day number: '); switch day case 1 day_str = 'SUNDAY'; case 2 day_str = 'MONDAY'; case 3 day_str = 'TUESDAY'; case 4 day_str = 'WEDNESDAY'; case 5 day_str = 'THURSDAY'; case 6 day_str = 'FRIDAY'; case 7 day_str = 'SATURDAY'; otherwise disp(['Illegaldaynumber:‘ num2str(day) '!']); day_str = ‘Invalid’; end disp(['Day name is ' day_str '.']); '!']); fprintf('Day number = %d\n',day_no); end day_no = 0; disp(['Illegal day name: ' day 131 65 The switch construct (cont.) qThe ctrl_expr and case_expr may be numerical values, string values, or logical values; qIf more than one case_expr should cause the same code to execute, then all those values may be included in a single set by enclosing them in curly-brackets or braces. Example: switch val case {1, 3, 5, 7, 9} disp(‘odd’); case {0, 2, 4, 6, 8} end disp(‘even’); 132 % Determine if a day is weekday or weekend day = input('Enter name of day: ','s'); day = upper(day); switch day case {'SUNDAY', 'SATURDAY'} disp('Weekend'); case {'MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY'} disp('Weekday'); otherwise disp(['Illegal day name: ', day, '!']); end 133 66 Determine if a day is weekday or weekend for a given name or number day = input('Enter name or number of a day: ','s'); day = upper(day); switch day case {'SUNDAY', 'SATURDAY', '6', '7'} disp('Weekend'); case {'MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY','1', '2','3','4','5'} disp('Weekday'); otherwise disp(['Illegal day name: ' day '!']); end 134 Ex. Seasons In most locations, spring months are March, April and May; summer is June, July, August; autumn is September, October, November; and winter is December, January, February. Write a program that 1. Have the user input a month (the number not the name) 2. Determine which season the month is in use a switch construct 3, 4, 5àspring 6, 7, 8àsummer 9, 10, 11àautumn 12, 1, 2àwinter otheràinvalid month 3. Print out which season the month is in. 135 67 month=input('please provide a month: '); switch month case {3,4,5} disp('spring'); case{9,10,11} ‘January’, ‘February’?) disp('autumn'); case{12,1,2} disp('winter'); otherwise end case {6,7,8} How to change the program to disp('summer'); accept month names (e.g. disp('invalid month'); 136 month=input('please provide a month: ', 's'); switch month case {'March','April','May'} disp('spring'); case {'June','July','August'} disp('summer'); case{'September','October','November'} disp('autumn'); case{'December','January','February'} disp('winter'); otherwise end disp('invalid month'); 137 68 Ex: Number of days in a month In 2014, there are 31 days in January, March, May, July, August, October, and December (1, 3, 5, 7, 8, 10, 12), 30 days in April, June, September, and November (4, 6, 9, 11), 28 days in February (2). Write a program that 1. Have the user input a month (the number not the name) 2. Determine the number of the days is in that month use a switch construct 1, 3, 5, 7, 8, 10, 12à31 days 4, 6, 9, 11à30 days 2à28 days otheràinvalid month 138 You many change the program used in the previous example (season of a month) month=input('please provide a month: '); switch month case {1,3,5,7,8,10,12} %31 days months disp(31); case 2 %28 days in Feb disp(28); case {4,6,9,11} %30 days months disp(30); otherwise end disp(‘Invalid Entry.’) 139 69 If construct or switch construct qSome branch structures can be implemented by either if construct or switch construct § Will show examples later qJust choose the one that can bring more convenience and readability. General rules: § Use switch construct if there are many branches (e.g. more than 3) and you can enumerate the possible values of control expression. § Use if construct when there are only a few branches (e.g. 2 or 3) or if it is not easy to enumerate the possible values of control expression. 140 x=input('Input a number:'); modulus = mod(x,2); if modulus==0 disp('Even number.'); else disp('Odd number.'); end x=input('Input a number:'); modulus = mod(x,2); switch modules case 0 disp('Even number.'); otherwise end disp('Odd number.'); 141 70 Switch construct is preferred day = input(Name of day: ','s'); day = upper(day); switch day case 'SUNDAY' day_no = 1; case 'MONDAY' day_no = 2; case 'TUESDAY' day_no = 3; case 'WEDNESDAY' day_no = 4; case 'THURSDAY' day_no = 5; case 'FRIDAY' day_no = 6; case 'SATURDAY' day_no = 7; otherwise disp('Illegal day'); day_no = 0; end disp(day_no); day = input(Name of day: ','s'); day = upper(day); if day == 'SUNDAY' day_no = 1; elseif day == 'MONDAY' day_no = 2; elseif day == 'TUESDAY' day_no = 3; elseif day == 'WEDNESDAY' day_no = 4; elseif day == 'THURSDAY' day_no = 5; elseif day == 'FRIDAY' day_no = 6; elseif day == 'SATURDAY' day_no = 7; else disp('Illegal day'); end day_no = 0; disp(day_no); 142 pounds to kilograms (if construct is preferred) pounds=input('Please input the weight in pounds:'); if pounds<0 disp('Invalid weight.'); else end kilograms=pounds/2.2; fprintf('It is %f kilograms.\n', kilograms); pounds=input('Please input the weight in pounds:'); switch pounds<0 case true disp('Invalid weight.'); otherwise kilograms=pounds/2.2; fprintf('It is %f kilograms.\n', kilograms); end 143 71 Signum function if x>0 y=1;
elseif x<0 y=-1; else y=0; end How to rewrite it with switch construct? 144 It is difficult to use switch construct here. Why? x = input ('Please enter x '); y = input ('Please enter y '); if x>=0 & y>=0
f=x+y; elseif x>=0 & y<0 f=x+y^2; elseif x<0 & y>=0
f=x^2+y;
else
f=x^2+y^2;
end
fprintf(‘f is %f\n’, f);
145
72

Outline
qBranch statements allow you to select and execute specified sections of code (called blocks) while skipping other sections of code
§If construct
üif … elseif …else … end
§Switch construct üswitch … case … end
§try/catch construct ütry… catch… end
146
try-catch construct
qThe try-catch construct is a special form branching designed to trap errors in program.
qNormally, when an error occurs, the program will be terminated abnormally.
qThe try-catch construct allows the programmer to handle the errors without aborting the program.
147
73

try-catch construct (cont.)
qThe try-catch constructs has the form:
• If an error occurs in a statement in the try section, instead of aborting the execution, the code in the catch section is executed and the program keeps running
148
Example
try y=x+1;
catch
disp(‘Error: x is not defined’);
x=input(‘Please input a value for x:’);
y=x+1;
end disp(y);
>> clear x
>> try_catch
Error: x is not defined
Please input a value for x:1
2
>> clear x
>> x=1;
>> try_catch
2
149
74

Example
try
y=x+[1 2 3];
catch
disp(‘Error: invalid value of x’);
x=input(‘Please input a value for x:’);
y=x+[1 2 3];
end disp(y);
>> x=[4 5]
>> try_catch
Error: invalid value of x
Please input a value for x:[4 5 6]
[5 7 9]
150
For LOOPS
• How to write for loops
• Common format of a for loop
• What is changing during the for loop
• How to figure out the values in variables affected in a for loop
•Loop index •Other variables
151
75

For loops
for index=expression Do something …
end
An index variable (the name is not necessarily index)
An expression generating an array. Control the number of iterations.
For each element (index) in the array, do something
152
For loops
for index=expression Do something …
end
qHow to generate an array? § List all the elements
§ Short-cut expression
§ linspace and other functions
§ Combination of the above three § MATLAB string
An expression generating an array. Control the number of iterations.
For each element (index) in the array, do something
153
76

For Loop Examples
forindex=[0246] disp(index);
forindex=[1 2 3]
disp(index); end
1 2 3
end
0 2 4 6
154
For Loop Examples
for index = 0:2:6 disp(index);
for index = 1:3
disp(index); end
1 2 3
end
0 2 4 6
155
77

For Loop Examples
for index = linespace(1,4,4) disp(index);
for index = [1 4 6 3] disp(index);
end
1 4 6 3
end
1 2 3 4
156
For Loop Examples
for index = [‘a’ ‘b’ ‘c’ ‘d’] disp(index);
for index = [‘ab’ ‘cd’] disp(index);
end
a b c d
end
a b c d
157
78

For Loop Examples
for index = ‘abcd’ disp(index);
end
a b c d
for index=eye(2)
disp(index);
1 0
0 1
end
158
For Loop Examples
for index = [3 6 1; 8:10; linspace(2,6,3)] fprintf(‘%d ‘, index);
end fprintf(‘\n’);
3 8 2 6 9 4 1 10 6
159
79

Common forms of for loops
for index = start:step:stop

end
Means:
• starting with k = 5, execute the statements between for … end;
• then increment k by 10 and execute the statements with k = 15;
etc. until k > 35.
• Then exit the loop (k=? at this point)
for k = 5:10:35
x=sqrt(k);
disp(x); end
160
for index = start:step:stop

end
qStep value may be negative (default is positive 1) qFor step > 0, loop does not execute if start > stop. qFor step < 0, loop does not execute if start < stop. qIf start = stop, loop executes once qIf the loop executes, index will be equal to the last element on the list 161 80 Ex: Simple for loops qWrite a for loop to print out all the even numbers from 2 to 100 (save the code into evennumbers.m) for index=2:2:100 disp(index); end qWrite a for loop to print out all the odd numbers from 1 to 100 (save the code into oddnumbers.m) for index=1:2:100 disp(index); end 162 How does the loop index change? for index = [0 2 4 6] end disp(index); for index = 1:3 end disp(index); 3 6 163 81 How does the loop index change? for index = linspace(1,4,4) end disp(index); for index = 'abcd' end disp(index); d 4 164 A variable may be changed repeatedly (changes on different parts of the variable) Evaluate xn = sin (n*pi/10) for n between 1 and 10 (in increments of 1). for n = 1:10 x(n) = sin(n*pi/10); end disp(x); 165 82 A variable may be changed repeatedly (changes accumulate) end Computing the factorial of a number: f(n) = 1*2*3*4...*n for index = start:stop ... = variable; variable = ...; n=input(‘Enter a number : ’); fact=1; % stores the factorial for index = 1:n fact = fact * index; end fprintf(‘factorial is %f\n’,fact); 166 Ex. Result of a loop x = [1 0 1 0 1 0]; for index = 1:6 x(index) = x(index)+1; end disp(x); What is the output? A.1 0 1 0 1 0 B.2 1 2 1 2 1 C. Syntax error D.1 1 1 1 1 1 167 83 Ex. Result of a loop x = [1 0 1 0 1 0]; for index = 2:2:6 x(index) = x(index)+1; end disp(x); What is the output? A.1 0 1 0 1 0 B.2 1 2 1 2 1 C. Syntax error D.1 1 1 1 1 1 168 Ex. Result of a loop sum = 0; for index=1:10 sum = sum + index; end disp(sum); A. Prints out 0; B. Prints out 45, which is equal to 1+2+3+4+5+6+7+8+9; C. Prints out 55, which is equal to 1+2+3+4+5+6+7+8+9+10; D. Causes a syntax error 169 84 Ex. Result of a loop a = []; forindex=[1 2 3 4 5] a=[a 2*index]; end disp(a); What is the output? A. 1 2 3 4 5 B. [] C. Error D. 2 4 6 8 10 170 Ex: Simple for loops qWrite a for loop to calculate the sum of all the even numbers from 1 to 100 (revise evennumbers.m) mysum = 0; for index=2:2:100 mysum = mysum + index; end disp(mysum) qWrite a for loop to calculate the product of all the odd numbers from 1 to 100 (revise oddnumbers.m) myproduct = 1; for index=1:2:100 myproduct = myproduct * index; end disp(myproduct); 171 85 Ex: Stock price A stock price goes up and down every day. What would the price be like if it changes following a regular pattern --- goesupby1%,downby1%,andthenupby1%and down by 1%? Suppose the initial price is 100 dollars. What's the price after 100 days? Would it be higher than 100? Still 100? or lower than 100? Write a program with a for loop to calculate it (save the program into stockprice.m). 172 stockprice.m Command window price = 100; for index=1:50 price = price * 1.01; price = price * 0.99; end disp(price); >> stockprice
99.5012
173
86

174
What if the price goes up/down by 10% every day?
Stockprice.m
price = 100;
for index=1:50
price = price * 1.1;
price = price * 0.9;
end
disp(price);
Command window
>> stockprice
60.5006
Ex: Euler’s number
The number e is an important mathematical constant that is the base of the natural logarithm. It is approximately equal to 2.71828, and is the limit of
(1 + ,+), as n approaches infinity (method 1), … 2.8
175
x=1:100; y1=ones(length(x))*exp(1); y2=(1+1./x).^x;
plot(x,y1, x,y2);
2.7 2.6 2.5 2.4 2.3 2.2 2.1
2
0 10 20 30 40 50 60 70 80 90 100
87

Ex: Euler’s number
The number e is an important mathematical constant that is the base of the natural logarithm. It is approximately equal to 2.71828, and is the limit of
(1 + ,+), as n approaches infinity (method 1), …
x=1:100;
y1=ones(1, length(x))*exp(1); y2=(1+1./x).^x;
diff = abs(y2-y1);
output = [x’ diff’]; disp(output);
176
Loops
• for loops
• Nestedforloops
• while loops, infinite loops
• break statement and continue statement
• An example – prime numbers
177
88

Nested for Loops
qfor loops can be nested (one inside another). qEach loop is closed with an end.
for index_outer=start_outer: inc_outer: final_outer …
for index_inner=start_inner:inc_inner:final_inner
….
end

end
178
Nested for Loops — example
A=[1 2 3;4 5 6]; for row = 1:2
for column = 1:3
B(row,column) = A(row, column);
end end
disp(B);
123 456
179
89

Nested for Loops — example
A=[];
for row = 1:2
for column = 1:3
A(row,column) = column;
end end
disp(A);
123 123
180
Nested for Loops — example
for row = 1:3
for column = 1:3
if row==column
A(row,column) = 1;
else
A(row,column) = 0;
end end
end disp(A);
Why are three end statements?
100 010 001
181
90

Nested for Loops — example
for x=1:3
for y=1:3
1
2 x=1
3
2
4 x=2 6
3
6 x=3 9
product=x*y;
disp(product);
end
end
182
Ex. What is the result of the nested loops
A=[];
for row = 1:2
for column = 1:3
A(row,column) = row;
end end
disp(A);
(A) 111 (B) 123 222 123
(C)
123 234
183
91

Ex. What is the result of the nested loops
a=[];
for x=1:3
for y=1:3
a(x,y)=x*y;
end end
disp(a);
123 123 147
(A) 2 4 6 (B) 4 5 6 (C)
369 789 369
258
184
Loops
• for loops
• Nested for loops
• while loops, infinite loops
• Array and loops
• break statement and continue statement
• An example – prime numbers
185
92

Loops in MatLab
qMATLAB support two different types of loops
qa for loop carries out a set of operations for each member in a list of items
§ Used when you can list the members
§ You know how many times the operations will be repeated.
qA while loop repeats a set of operations while a
condition is met (i.e. until the condition is not met).
§ The program should guarantee that the condition will be eventually violated in the future to finish the loop. How?
üChange the condition in the loop
§ You may now know how many times the operations will be repeated.
186
while Loop
qA while loop is a block of statements that are repeated indefinitely as long as some condition is satisfied.
qGeneral Form
187
93

You may not always know the number of iterations….
while input(‘Continue(Y/N)?’, ‘s’) == ‘Y’ the code playing rock-paper-scissors
end
188
You may not always know the number of iterations….
Print all the positive integer 𝑥 with 𝑒( < 1000 1 2 3 4 5 Do you know how many integers are there? 6 index=1; while exp(index)<1000 disp(index); index=index+1; end 189 94 Infinite loop qAn infinite loop (also known as an endless loop or unproductive loop) is a sequence of instructions in a computer program which loops endlessly. 1 1 1 1 1 1 ... while true do something here; end index=1; while index<=3 disp(index); end 190 for index = 1:3 disp(index); end 1 2 3 index=1; while index<=3 disp(index); index=index+1; end 191 95 Value of index variable when loop finishes 3 4 for index = 1:3 end disp(index); index=1; while index<=3 index=index+1; end disp(index); 192 for index = 1:2:9 disp(index); end 1 3 5 7 9 index=1; while index<=9 disp(index); index=index+2; end 193 96 for index = 1:2:9 end disp(index); 9 11 index=1; while index<=9 index=index+2; end disp(index); 194 x=[1 0 1 0 1 0]; for index = 1:6 x(index) = x(index)+1; end disp(x); x=[1 0 1 0 1 0]; index=1; while index<=6 x(index) = x(index)+1; index=index+1; end disp(x); 195 97 Ex: Simple while loops qWrite a while loop to print out all the even numbers from 1 to 100 (save the code into evennumbers.m) for index=2:2:100 disp(index); end index=2; while index<=100 disp(index); index = index + 2; end How to implement it using a while loop? 196 Ex: Simple while loops qWrite a while loop to print out all the odd numbers from 1 to 100 (save the code into oddnumbers.m) for index=1:2:100 disp(index); end index=1 while index<100 disp(index); index = index + 2; end How to implement it using a while loop? 197 98 for k = 5:10:35 x=sqrt(k); disp(x); end k=5; while k<=35 x=sqrt(k); disp(x); k=k+10; end 198 Evaluate xn = sin (n*pi/10) for n between 1 and 10 (in increments of 1). for n = 1:10 x(n) = sin(n*pi/10); end disp(x); n=1; while n<=10 x(n) = sin(n*pi/10); n=n+1; end disp(x); 199 99 Ex: Simple while loops q Write a while loop to calculate the sum of all the even numbers from 1 to 100 (revise evennumbers.m) mysum = 0; index = 2; while index<=100 mysum = mysum + index; index = index + 2; end disp(mysum) mysum = 0; for index=2:2:100 mysum = mysum + index; end disp(mysum) 200 Ex: Simple while loops q Write a while loop to calculate the product of all the odd numbers from 1 to 100 (revise oddnumbers.m) myproduct = 1; index = 1; while index<100 myproduct = myproduct * index; index = index + 2; end disp(myproduct); myproduct = 1; for index=1:2:100 myproduct = myproduct * index; end disp(myproduct); 201 100 Computing the factorial of a number: f(n) = 1*2*3*4...*n n=input('Enter a number : '); fact=1; %factorial of a given number for index = 1:n fact = fact * index; end fprintf('factorial is %f\n',fact); 202 Computing the factorial of a number: f(n) = 1*2*3*4...*n n=input('Enter a number: '); fact=1; %factorial of a given number index=1; while index<=n fact=fact*index; index=index+1; end fprintf('factorial is %f\n',fact); 203 101 some in-class exercises a = [1 4 6 3]; index= 1; while index <= length(a) ele = a(index); fprintf('%d ', ele); index = index+1; end A. Error B. Print out 14, which is equal to 1+4+6+3 C.Printout146 3 D. Printout 1 4 6 204 some in-class exercises index = 1; sum = 0; while index <= 10 sum = sum + index; index = index + 1; end disp(sum); A. Prints out 0; B. Prints out 45, which is equal to 1+2+3+4+5+6+7+8+9; C. Prints out 55, which is equal to 1+2+3+4+5+6+7+8+9+10; D. Causes a syntax error 205 102 Ex: Stock price A stock price goes up and down every day. What would the price be like if it changes following a regular pattern --- goesupby1%,downby1%,andthenupby1%and down by 1%? Suppose the initial price is 100 dollars. What's the price after 100 days? Would it be higher than 100? Still 100? or lower than 100? Write a program with a for loop to calculate it (save the program into stockprice.m). 206 stockprice.m price = 100; for index=1:50 price = price * 1.01; price = price * 0.99; end disp(price); price = 100; index = 1; while index<50 price = price * 1.01; price = price * 0.99; index = index + 1; end disp(price); while loop? 207 103 Loops • for loops • Nested for loops • while loops, infinite loops • Array and loops • break statement and continue statement • An example – prime numbers 208 Array operations vs. loops qArray operations can be implemented with loops qE.g. add 1 to each element in an array arr Array operation: Loop: Concise and simpler 10 times faster arr = arr+1; for index=1:length(arr) arr(index)=arr(index)+1; end 209 104 Array operations vs. loops qArray operations can be implemented with loops qE.g. add two arrays (arr1 and arr2) Array operation: Loop: 64 times faster arr3 = arr2+arr1; for index=1:length(arr2) arr3(index)=arr2(index)+arr1(index); end 210 Logical Arrays & Mask qScalars and arrays of logical data are created as the output of relational and logical operators. qFor example a = [1 2 3; 4 5 6; 7 8 9]; b = a > 5;
b = [0 0 0; 0 0 1; 1 1 1];
qLogical arrays can serve as a mask for arithmetic operations.
(1) A mask is an array that selects the elements of another array for use in an operation;
(2) The specified operation will be applied to the selected elements and not to the remaining elements.
211
105

>>r=[8 12 9 4 23 19 10]
r=
8 12 9 4 23 19 10
>> s=r<=10 s= 1011001 >> t=r(s) t=
8 9 4 10
>>t=r([1 0 1 1 0 0 1])
>> whos s
Name Size Bytes Class Attributes
s 1×7 7 logical
Error!
212
>>s=[1 0 1 1 0 0 1]
>> t=r(s) >> whos s
Error!
Name Size Bytes Class Attributes s 1×7 56 double
>> s=logical(s) >> t=r(s)
t=8 9 4 10
>> s=[true false true true false false true] >> t=r(s)
t=8 9 4 10
>> w=r(r<=10) w= 8 9 4 10 213 106 >>r=[8 12 9 4 23 19 10]
r=
8 12 9 4 23 19 10
>> s=r<=10 s= 1011001 >> r(s)=0 r=
0 12 0 >>r(s)=r(s)+1
r=
0 23 19 0 1 23 19 1
1 12 1
214
In-class exercises
a = [1 2 3; 4 5 6; 7 8 9]; % normal array b = a > 5; % logical array
>> a(b)=0
???
>>a(b)=a(b)+1 ???
>>a(~b)=0 ???
215
107

Ex. Array operations vs. loops
Step 1. write a program array.m
Step 2: write a program loop.m
Step 3: Compare Performance
Command window
tic
arr1=ones(1,10000000);
arr2=arr1*2;
toc
>> clear
>> array
>> clear
>> loop
tic
for index = 1:10000000
arr1(index)=1;
arr2(index)=arr1(index)*2;
end
toc
216
Loops
• for loops
• Nested for loops
• while loops, infinite loops
• Array and loops
• break statement and continue statement
• An example – prime numbers
217
108

Break & Continue
qThe break statement terminates the execution of a loop and passes
control to the next statement after the end of the loop
qThe continue statement terminates the current iteration and starts a new one
qBoth are usually used in conjunction of an if statement
218
Example
while true
answer = input(‘more number?’); if answer == 0
break; end
end
What’s the purpose of these statements?
219
109

continue statement
for index=1:10
disp(‘Tom’);
continue;
disp(‘Jerry’); Tom
end Tom Tom Tom Tom
Tom Tom Tom Tom Tom
Skip the unfinished statements in current iteration
220
In-class exercises
ii = 1;
b = [];
while ii <= 5 if (ii == 2) break; end b(ii) = ii; ii = ii + 1; end disp(b); What is the output? b = []; for ii = 1:5 if (ii == 3) continue; end b(ii) = ii; end disp(b); What is the output? 221 110 What is the output? 50 for index=1:100 if index==50 break; end end disp(index); a=[1 2 3; 4 5 6; 7 8 9] for x=1:3 for y=1:3 disp(a(x, y)); if y ==2 break; end end end 222 continue statement while true a=input('Enter a value: '); if a<0 disp('Must be positive!'); disp('Try again'); continue elseif a==0 disp('Terminating'); break; end disp(log(a)); 223 end 111 In-class exercises How many times will the disp() function be called when the following program is executed? for index = 1:10 if index == 6 break; end if index == 3 continue; end disp(index); end A. 5 B. 6 C. 10 D. 4 224 In-class exercises How many times will the disp() function be called when the following program is executed? for index = 1:10 if index >=3 & index <=7 continue; end disp(index); end A. 3 B. 7 C. 10 D. 5 225 112 User Defined Function • A function is a piece of computer code that accepts an input argument from the user and provides output to the program. • Given an inputàDo whatever you like (functionality)àGet output 226 User-Defined Functions qWhen you create/define a function: function [outarg1, outarg2, ...] = funcName(inarg1, inarg2, ...) % (H1 comment and help block are optional) ... outarg1 = ... outarg2 = ... ... (return) % return and end are in parenthesizes because they (end) % are optional. Remove parenthesizes in real programs § Save the function into funcName.m 227 113 User-Defined Functions 1 output & 1 input function result=funcName(x) ... 1 output & 2 inputs function result=funcName(x,y) ... 2 output & 1 input function [result1,result2]=funcName(x) ... 228 Special case: a function without input and output function funcName() statements 229 114 Examples function result=signum(inarg) if inarg > 0
result = 1; else
result = 0;
function [dist,vel,accel]=motion(t) accel=0.5*t;
vel=0.5*accel*t^2;
dist=vel*t^3/6;
230
Call User-Defined Functions
• 1output&1input
– myresult=funcName(x); – funcName(x);
• 1output&2inputs
– myresult=funcName(x,y); – funcName(x,y);
• 2output&1input
– [myresult1, myresult2]=funcName(x)
• Inputargumentscanbeconstants,variablesor expressions
• Outputargumentsmustbevariables – left hand side of =
231
115

Function call
3
1
tic; a=primes(4000000* 2); toc;
function p = primes( n )
… 2
p = p(p>0);
232
UDF — Example
• max(x): Finds the largest value in a vector x.
• min(x): Finds the smallest value in a vector x.
• e.g.
>> a=[1 5 3 7 6 2]; >> max(a)
>> min(a)
• write our own max2() and min2() functions
233
116

max2.m
function outarg=max2(inarg)
outarg = inarg(1);
for index = 2:lengh(inarg)
if inarg(index) > outarg
outarg = inarg(index);
end end
234
min2.m
function outarg=min2(inarg)
outarg = inarg(1);
for index = 2:lengh(inarg)
if inarg(index) < outarg outarg = inarg(index); end end 235 117 Why do we need UDFs? • Top-down design • Work on the algorithm framework first. Then, implement functions • Functions are building blocks • Reduce design complexity 236 Why do we need UDFs? • Top-down design • Simplify testing • Each function can be tested individually • Reuse code • Functions can be used by other functions and scripts • Isolation and data hiding 237 118 Isolation and date hiding (1/3) • The variables in the main program are not visible to the function • The variables in the main program cannot be modified by anything occurring in the function 238 mainprog.m myfunc.m >>mainprog
a = ‘hello world!’;
myfunc()
function myfunc()
disp(a);
239
119

mainprog.m
myfunc.m
>>mainprog
a = ‘hello world!’;
myfunc();
disp(a);
function myfunc()
a=‘byebye’;
240
Isolation and date hiding (2/3)
• Each function has its own local workspace myscript.m
>>clear >>myscript
Check your MATLAB workspace
A = 1;
B = 10:2:20;
C = ‘hello world!’;
241
120

Isolation and date hiding (2/3)
• Each function has its own local workspace myfunc.m
>>clear >>myfunc
Check your MATLAB workspace
function myfunc()
A = 1;
B = 10:2:20;
C = ‘hello world!’;
242
Isolation and date hiding (3/3)
• Theonlyinterfacebetweenafunctionandotherfunctionsor programs: input and output arguments
• Benefits
• Debuggingiseasier
• Programming errors in a function will not affect other parts of the caller (except the output arguments)
• Correctness of a function will not be affected by other functions or callers
• Mainprogramandvariousfunctionsmaybewrittenbydifferent programmers
• They may use the the variable names they like without worrying about conflicts
243
121

Why do we need UDFs?
• Top-down design • Simplify testing
• Each function can be tested individually • Reuse code
• Functions can be used by other functions and scripts
• Isolation and data hiding
244
Ex: lettergrade function
Create a function to determine test grades based on the score and assuming a single input into the function.
90-100 à A 80-89 àB 70-79 àC 60-69 àD <60 àE Save the function into lettergrade.m (lettergrade cannot be a variable name) 1 output & 1 input function grade=lettergrade(x) ... 245 122 Finish your program... function grade=lettergrade(x) if x>= …
grade=’A’; elseif x>= …
grade=’B’; elseif x>= …
grade=’C’;
… end
Test it.
90-100 à A 80-89 àB 70-79 àC 60-69 àD <60 àE >>lettergrade(10) >> lettergrade(82) >> lettergrade(95) …
246
Subfunctions and nested function
247
123

Example
• Write a single function maxmin() to calculate both the largest number and the smallest number in a vector.
• Method 1: combining max2() and min2()
248
function outarg=max2(inarg)
outarg = inarg(1);
for index = 2:lengh(inarg)
if inarg(index) > outarg
outarg = inarg(index);
end end
function outarg=min2(inarg)
outarg = inarg(1);
for index = 2:lengh(inarg)
if inarg(index) < outarg outarg = inarg(index); end end 249 124 function [outarg1, outarg2]=maxmin(inarg) outarg1 = inarg(1); outarg2 = inarg(1); for index = 2:lengh(inarg) if inarg(index) > outarg1
outarg1 = inarg(index);
end
if inarg(index) < outarg2 outarg2 = inarg(index); end end 250 function [outarg1, outarg2]=maxmin(inarg) outarg1 = max2(inarg); outarg2 = min2(inarg); function outarg=max2(inarg) outarg = inarg(1); for index = 2:lengh(inarg) if inarg(index) > outarg
outarg = inarg(index); end
end
function outarg=min2(inarg) outarg = inarg(1);
for index = 2:lengh(inarg)
if inarg(index) < outarg outarg = inarg(index); end end 251 125 Subfunctions qIf more than one function is present in a file, the top function is a normal or primary function, while the ones below it are subfunctions. qThe file containing the program is named after the primary function. qSubfunctions in a program are supporting functions only for this program. § Functions for function 252 Subfunctions cannot be called outside of the program myfunc.m function myfunc() mysubfunc(); function mysubfunc() disp('subfunc is called'); >>myfunc >>mysubfunc
253
126

Nested Functions
qNested functions are functions that are defined entirely within the body of another function, called the host function.
host_function

nested_function_1
%variables only visible here end %required
nested_function_2 end
end
254
255
127

function [outarg1, outarg2]=maxmin(inarg)
outarg1 = max2(inarg);
outarg2 = min2(inarg);
function outarg=max2(inarg)
outarg = inarg(1);
for index = 2:length(inarg)
if inarg(index) > outarg
outarg = inarg(index);
end
end end
function outarg=min2(inarg)
outarg = inarg(1);
for index = 2:length(inarg)
if inarg(index) < outarg outarg = inarg(index); end end end end 256 function [outarg1, outarg2]=maxmin(inarg) outarg1 = max2(inarg); outarg2 = min2(inarg); function outarg=max2(inarg) outarg = inarg(1); for index = 2:length(inarg) if inarg(index) > outarg end outarg = inarg(index);
end end
function outarg=min2(inarg) outarg = inarg(1);
for index = 2:length(inarg)
if inarg(index) < outarg outarg = inarg(index); end end end end 257 128 function [outarg1, outarg2]=maxmin(inarg) outarg1 = max2(); outarg2 = min2(); function outarg=max2() outarg = inarg(1); for index = 2:length(inarg) if inarg(index) > outarg end outarg = inarg(index);
end end
function outarg=min2()
outarg = inarg(1);
for index = 2:length(inarg)
if inarg(index) < outarg outarg = inarg(index); end end end end 258 function [outarg1, outarg2]=maxmin(inarg) outarg1 = max2(); outarg2 = min2(); function outarg=min2() outarg = inarg(1); for index = 2:length(inarg) if inarg(index) > outarg
outarg = inarg(index); end
end
function outarg=max2() X outarg = inarg(1);
for index = 2:length(inarg)
if inarg(index) < outarg outarg = inarg(index); end end 259 129 subfunction vs. nested function qSubfunctions cannot access variables in primary function qNested functions can access variables in their host function § May bring some convenience but at the cost of isolation. üE.g. when the function needs a large number of inputs and generate lots of outputs, it is better to use nested functions. 260 Can a function call itself? • Recursion: a function is said to be recursive if the function calls itself. • Factorial Function • N! = – N(N-1)! N>=1 –1 N=0
261
130

function result=factorial3(x)
fprintf(`%d\n’,x);
if x==0
result=1;
else
result=x*factorial3(x-1);
end
fprintf(‘factorial of %d is %d\n’, x,
result);
262
Share variables between functions and between functions and programs
qA global variable is declared with the global statement.
global var1 var2 var3 …
qSuppose a variable is declared to be global in a function, if the same variable is declared to be global in another function or in another program, then the variables refer to the same thing
263
131

global a b out;
a = 2;
b = [6 4];
fprintf(‘a=%d, b=%d %d\n’, a,b);
myfunc();
fprintf(‘a=%d, b=%d %d, out=%d\n’, a, b, out);
function myfunc()
global a b out;
fprintf(‘a=%d, b=%d %d\n’, a, b);
a=a*2;
b = b ./ 2;
out = a + b(1) + b(2);
fprintf(‘a=%d, b=%d %d, out=%d\n’, a, b, out);
Declare variables
global
264
global a b out;
a = 2;
b = [6 4];
fprintf(‘a=%d, b=%d %d\n’, a,b);
myfunc();
fprintf(‘a=%d, b=%d %d, out=%d\n’, a, b, out);
function myfunc()
global a b out;
fprintf(‘a=%d, b=%d %d\n’, a, b);
a=a*2;
b = b ./ 2;
out = a + b(1) + b(2);
fprintf(‘a=%d, b=%d %d, out=%d\n’, a, b, out);
265
132

Persistent Variable
qPersistent variables will not be destroyed after the function finishes execution.
§ Their values persist across different function calls
qA persistent variable is declared with the persistent
statement
persistent var1 var2 var3 …
qA primary functionality of persistent variable is to count the number of times a function has been called.
266
main.m
myfunc.m
a = 1000;
for i = 1:a
myfunc();
end
function myfunc() persistent num
if isempty(num)
num = 1; else
num = num + 1;
end
fprintf(‘this functions has been called %d
times\n’, num);
267
133

function outarg=min2(inarg)
persistent outarg;
if isempty(outarg)
outarg = inf;
end
for index = 1:lengh(inarg)
if inarg(index) < outarg outarg = inarg(index); end end >> min2([98 97] >> min2([100 99] >>
268
Lab session
qArray/Matrix qPlot
qTable qReview
269
269
134