代写 C math matlab scala Programming MATLAB

Programming MATLAB
Paul Cotofrei
information management institute master of science in finance
2018

Outline
Vectors and Matrices
Indexing
Operators and functions Logical vectors/matrices

Matrices
􏰁 Amatrixisadatastructureusedtostoreasetofvaluesofthesametype;every value is stored in an element
􏰁 MATLABstandsfor”matrixlaboratory”
􏰁 Amatrixlookslikeatable;ithasbothrowsandcolumns
􏰁 Amatrixwithmrowsandncolumnsiscalledm×n;thesearecalledits dimensions; e.g. this is a 2 × 3 matrix:
􏰁 ThetermarrayisfrequentlyusedinMATLABtorefergenericallytoamatrixora vector
􏰁 Anarraymayhavemorethantwodimensions(e.g.3×2×3)andit’sdenoted as a multidimensional array
9
7
5
3
6
8

Vectors and Scalars
􏰁 Avectorisaspecialcaseofamatrixinwhichoneofthedimensionsis1 􏰁 arowvectorwithnelementsis1×n,e.g.1×8:
􏰁 acolumnvectorwithmelementsism×1,e.g.3×1:
9
7
5
3
6
8
0
12
9
7
5
􏰁 Ascalarisanevenmorespecialcase;itis1×1,orinotherwords,justasingle value
9

Creating Row Vectors
􏰁 Directmethod:putthevaluesyouwantinsquarebrackets,separatedbyeither commas or spaces
» v = [1 2 3 4] v=
1234
» v = [1,2,3,4]
v=
1234
􏰁 Colonoperator:iteratesthroughvaluesintheformfirst:step:last
» v = 5:3:14 v=
5 8 11 14
» v = 5:3:16
v=
5 8 11 14
» v = 2:5 v=
2345 » v = 4:-1:1
v=
4321
% no step value => step 1
% negative step value

Functions generating row vectors
􏰁 Thefunctionlinspacecreatesalinearlyspacedvector; linspace(x,y,n) creates a vector with n values in the inclusive range from x to y
􏰁 e.g. linspace(4,7,3) creates a vector with 3 values including the 4 and 7 so it returns [4, 5.5, 7]
􏰁 linspace(x, y, n) is equivalent with x:(y-x)/(n-1):y
» v = linspace(0, 1, 6) v=
0 0.2000 0.4000 0.6000 0.8000 1.0000
» v = 0:0.2:1
v=
0 0.2000 0.4000 0.6000 0.8000 1.0000
􏰁 If n is omitted, the default is 100 points
􏰁 Thefunctionlogspacecreatesalogarithmicallyspacedvector; logspace(x,y,n) creates a vector with n values in the inclusive range from 10x to 10y
􏰁
» v = logspace(2,4,3) v=
100 1000 10000
􏰁 If n is omitted, the default is 50 points

Column Vectors
􏰁 Acolumnvectorisanm×1vector
􏰁 Directmethod:cancreatebyseparatingvaluesinsquarebracketswith
semicolons e.g.
» v = [4; 7; 2] v=
4 7 2
􏰁 Wecannotdirectlycreateacolumnvectorusingvectorgeneratingfunctions,but we can create a row vector and then transpose it to get a column vector using the transpose operator ’
» v = linspace(2, 10, 5)’ v=
2 4 6 8 10

Generating Matrices
􏰁 Enumeratetheelementsusingsquarebrackets
􏰁 Row separator : semicolon (;)
􏰁 Columns separator : space or comma (,)
» a = [1, 5, 9, 7; 6 4 8 2] a=
1597 6482
􏰁 Canuseanymethodtogetvaluesineachrow(anymethodtocreatea row vector, including colon operator)
» mat = [1:3; 6 11 -2]
mat =
123
6 11 -2
􏰁 Theelementsofamatrixmaybeexpressions
􏰁 Amatrixmustberectangular!(theexpression raise en error)
» a = [-2.8 sqrt(51) (4 + 15)/sin(pi/2); linspace(6, 9, 3)];
» b = [1,2; 3,4,5];

Commands to create/manipulate matrices
size(A)
Returns the size of each dimension of a matrix
size(A,1)
Returns the number of rows
size(A,2)
Returns the number of columns
length(A)
Returns the size of the longest dimension of a matrix
numel(A)
The total number of elements in a vector or matrix.
linspace(x, y, n)
Generates linearly spaced sequences
logspace(x, y, n)
Generates logarithmically spaced sequences
zeros(n, m)
Generates a matrix n × m of zeros
ones(n, m)
Generates a matrix n × m with all elements being 1
eye(n)
Generates the identity matrix In
diag()
Generate a diagonal matrix from a vector. Extract the diagonal of a matrix
Remark: If a function generating a matrix receives one argument (as ones(n), the result is a square matrix n × n. To generate a vector, give both dimensions, as ones(n, 1) or ones(1, n).
Use for more information
» doc elmat

Random matrices
􏰁 randorrand(1):generateanumberfromtheuniform distribution over (0, 1)
􏰁 rand(n)orrand(m,n):generateamatrixn×norm×nof uniformly distributed numbers in (0, 1)
􏰁 a + (b-a)*rand(m,n) : uniformly distributed numbers in the interval (a, b)
􏰁 randn(m, n) : generate a matrix m × n of standard normal distributed numbers (mean = 0, standard deviation = 1)
􏰁 mu + sigma*randn(m, n) : normal distributed numbers, with mean = mu and standard deviation = sigma
􏰁 randi(k, m, n) : generate a matrix m × n of uniformly distributed integers in [1, k ]
􏰁 randperm(n):generatearandompermutationofthenumbers {1, 2, …, n}

Outline
Vectors and Matrices
Indexing
Operators and functions Logical vectors/matrices

Vector indexing
􏰁 Theelementsinavectorarenumberedsequentially;each element number is called the index, or subscript and are shown above the elements here:
􏰁 Note:MATLABvectorindicesalwaysstartwith1andmaynot be 0 or negative
􏰁 Refertoanelementusingitsindexorsubscriptinparentheses, e.g. vec(4) is the 4th element of a vector vec (assuming it has at least 4 elements)

Matrix indexing
􏰁 Referencetoaspecificelement:matrixvariablenamefollowedbytheindexof the row, and then the index of the column, in parentheses.
􏰁 This reference is called subscripted indexing
􏰁 ALWAYS refer to the row first, column second
􏰁 Rowsandcolumnsarealwaysnumberedstartingat1
􏰁 Toreferasubsetofamatrix,useindexvector(avectorofindices)
􏰁 Thecolonoperator(:)specifyarangeorALL
􏰁 ’end’specifythemaximumsubscript

Matrix indexing
􏰁 Linearindexing:onlyusingoneindexintoamatrix(MATLAB will unwind it column-by column)
􏰁 Theindexmaybeascalar,avector,oramatrix(inthelastcase, use [] to create the matrix of subscripts for indexing)

Vector indexing – Examples
» x = [2, 5, -6, 10, 3, 4];
» x(3)
ans =
-6
» x(end)
ans = 4
» x(end-3:end)
ans =
-6 10 3 4
» x(1:3:end)
ans =
% last four elements
2 10
» x(1:2:end)
ans =
% every third entry
2 -6 3
» x(end:-1:1)
ans =
4 3 10
% every second entry
-6 5 2 % list backwards

Matrix manipulation – Examples
􏰁 Buildingamatrixcolumn-wise

Matrix manipulation – Examples
􏰁 Transposingamatrix

Matrix manipulation – Examples
􏰁 Thematrixdimensionsaredynamic!
􏰁 a matrix can be extended by assigning an element outside bounds (the
undefined elements are assigned as 0) 􏰁 Add/deletearow/column

Matrix manipulation – Examples
􏰁 Replacingrowsorcolumns

Matrix manipulation – Examples
􏰁 Insertingrowsorcolumns

Matrix manipulation – Examples
􏰁 Concatenatingmatrices

Matrix massage
reshape(A,m,n)
Change size of matrix A to have dimension m x n. An error results if A does not have m x n elements
rot90(A)
Rotates a matrix 90 degrees counter-clockwise
shiftdim(A,n)
Shift the dimension of A by n. Generalizes trans- pose for multi-dimensional matrices
fliplr(A)
Flips columns of a matrix from left to right
flipud(A)
Flips rows of a matrix up to down
repmat(A, m, n)
Replicates a matrix; creates m × n copies of the ma- trix

Matrix manipulation – Examples
􏰁 Replicatingmatricesusingrepmat

Matrix manipulation – Examples
􏰁 Reshapingamatrixoravector

Matrix manipulation – Examples
􏰁 Rotateandflip

Outline
Vectors and Matrices
Indexing
Operators and functions
Logical vectors/matrices

Arithmetic operators
Matrix Operators
􏰁 Matrixaddition(+):thetwomatricesmusthavethesame dimensions(C=A+B,cij =aij +bij)
􏰁 Matrix multiplication (∗) : An×m ∗ Bm×p = Cn×p (inner dimensions must be equal) – cij = 􏰇mk=1 aik ∗ bkj
􏰁
􏰁 Matrixexponentiation(ˆ):AˆpmeansA∗A∗..∗A(ptimes)
􏰁 Aˆ(-1) is equivalent with the inverse of A
􏰁 Leftdivision(\):thematriceequationAX=Bhasthesolution
»A = [1 2 3; 4 5 6]; B = [1 2; 3 4; 5 6]; » C = A*B
C=
22 28 49 64
» X = A\B
» doc ops

Arithmetic operators
Element-by-Element Operators
􏰁 Elementwisemultiplication(.∗):thetwomatricesmusthavethe same dimensions
􏰁 Resulting element : product of the corresponding elements in the multiplied matrices
» A = [1 2 3; 4 5 6]; B = [2 2 2; 3 3 3]; » C = A .* B
C=
246 12 15 18
􏰁 Elementwiseexponentiation(.ˆ):
􏰁 Amn , p integer : A.ˆp means (ap ), and p.ˆA means (paij )
ij
􏰁 Elementwisedivision(.\)or(./):A.\Bmeans(aij\bij);A./Bmeans (aij /bij )
􏰁 Amn , Bmn : A.ˆB means (abij ) ij

Examples
» a = [2 3 4 5];
» a.ˆ2 % [2ˆ2, 3ˆ2, 4ˆ2, 5ˆ2]
ans =
4 9 16 25
» 2.ˆa % [2ˆ2, 2ˆ3, 2ˆ4, 2ˆ5]
ans =
4 8 16 32
» A = [1 2; 3 4] A=
12
34
» [A, A.ˆ2; Aˆ2, A*A] ans =
% form sub-blocks
1214 3 4 916 7107 10
15 22 15 22
» B = 10.ˆA;
» [B, log10(B)]
ans =
10 100 12 1000 10000 3 4
% note Aˆ2 = A*A

Scalar expansion
􏰁 Whenascalarisaddedtoamatrix,asinA+c,thescalaris expanded to a matrix with the same size as A and with all its elements equal c.
􏰁 Whenascalarismultipliedwithamatrix,(asc∗A),thenthe expanded matrix of the scalar is multiplied element-by-element with A

Functions on vectors
max(v)
The maximum element of a real vector
min(v)
The minimum element of a real vector
sum(v)
The sum of the elements of a vector
prod(v)
The product of the elements of a vector
diff(v)
The difference between successive elements of a vector
mean(v)
The average of the elements of a vector
std(v)
The standard deviation of the elements of a vector
cumsum(v)
The cumulative sum between successive elements of a vector
cumproduct(v)
The cumulative product between successive elements of a vector
Note: When applied to a matrix, a vector function f (·) returns a row vector containing the results of the function applied to each column of the matrix

Min, Max : Examples
» v = [4 -2 5 11];
» min(vec)
ans =
-2
» [min_v, i] = min(vec);
» disp(min_v);
-2
» disp(i);
2
» mat = randi([1, 10], 2,4)
mat =
6574
3 7 4 10
» max(mat)
ans =
6 7 7 10
» max(max(mat))
ans =
10
» max(mat(:))
ans =
10
» [max_m, k] = max(mat(:))
max =
10 k=
8
» [i, j] = ind2sub([2, 4], k) i=
2 j=
4

Sum, Cumsum : Examples
» vec = [4 -2 5 11];
» sum(vec)
ans =
18
» cumsum(vec)
ans =
4 2 7 18
» mat = randi([1, 10], 2,4)
mat =
1 10 1 4
9 837 » sum(mat)
ans =
10 18 4 11
» cumsum(mat)
ans =
1101 4 10 18 4 11
» s = sum(sum(mat)) s=
43
» s = sum(mat(:)) s=
43
» cumsum(mat(:))
ans =
1 10 20 28 29 32 36 43
􏰁 ForamatrixA,sum(A)returnsthesumforeachcolumn;cumsum(A) shows the cumulative sums as it iterates through the rows

Note on vector functions
􏰁 Bydefault,avectorfunctionf(·)appliedonamatrixAreturnsarowvector containing the results of the function applied to each column of the matrix, i.e [f (A(:, 1), f (A(:, 2), …, f (A(:, end )]
􏰁 Howtogetacolumnvectorcontainingtheresultsofthefunctionappliedtoeach row of the matrix ?
􏰁 Solution one: use the transpose operator
􏰁 Solution two: call the function f (·) with a supplementary parameter (the dimension)
» v = f(A’);
» v = v’;
» A = [1 2 3; 4 5 6];
» sum(A)
ans =
579
» sum(A, 1)
ans = 579
» sum(A, 2)
ans =
6 15
» mean(A)
ans =
2.5 3.5 4.5
» mean(A, 2)
ans = 2 5
» max(A) ans =
456
» max(A, [], 2)
ans = 3 6

dot : Example
􏰁 Thedotproductorinnerproductoftwovectorsaandbisdefinedas a1 b1 + a2 b2 + a3 b3 + · · · + an bn . The built-in function dot implements the inner product
» a = [2 4 0 9];
» b = [5 -2 3 1];
» dot(a, b)
ans =
11
» A = [1 2 3;4 5 6;7 8 9]; » B = [9 8 7;6 5 4;3 2 1]; » C = dot(A, B)
C=
54 57 54
% The result, C, contains three separate dot products corresponding
to the dot products between the columns of A and B; e.g. C(1) is
the inner product between the columns A(:, 1) and B(:, 1)
» C = dot(A, B, 1); % it’s equivalent with dot(A, B)
» C = dot(A, B, 2)% dot product of the corresponding rows of A and B C=
46 73 46

sort : Example
» a = [9 0 -7 5 3 8 -10 4 2]; » b = sort(a)
b=
-10 -7 0 2 3 4 5 8 9 » x = randn(5,3)
x=
0.0294 -1.0928 1.6686
-1.5732 -0.1697 -0.4750
-1.1899 0.5751 -0.7604
1.8115 0.6548 -1.1189
0.0426 -0.0969 0.1698
» sort(x) % sort each column in ascending order
ans = % also, sort(x, ’ascend’) or sort(x, ’descend’)
-1.5732 -1.0928 -1.1189
-1.1899 -0.1697 -0.7604
0.0294 -0.0969 -0.4750
0.0426 0.5751 0.1698
1.8115 0.6548 1.6686

sort : Example
» [x2,i2] = sort(x(:,2),’descend’);
» [x2,i2]
0.6548
0.5751
-0.0969
-0.1697
-1.0928
% sort column 2 in descending order
4 % x2 = sorted column
3 % i2 = sorting index
5
2
1
» x_sort = x(i2,:) % sort x relative to column 2
1.8115 0.6548 -1.1189
-1.1899 0.5751 -0.7604
0.0426 -0.0969 0.1698
-1.5732 -0.1697 -0.4750
0.0294 -1.0928 1.6686
To sort the rows of a matrix, use sort(A, 2)

Built-in functions with matrix argument
􏰁 Mostmathfunctionsadmitscalarorarrayinputargumentsand operate on each element of the array
» x = [0, pi/4, pi/3, pi/2, pi];
» sin(x)
ans =
0 0.7071 0.8660 1.0000 0.0000
» x = [2.1, 2.8, -3.1; -3.5, 4.5, -1.4]; » y = exp(x)
y=
8.1662
0.0302
» z = log(y)
16.4446 0.0450
90.0171 0.2466
% note log(exp(x)) = x
z=
2.1000 2.8000 -3.1000
-3.5000 4.5000 -1.4000
» [fix(z); floor(z); round(z)]
ans =
2 2 -3
-3 4 -1
2 2 -4
-4 4 -2
2 3 -3
-4 5 -1

Outline
Vectors and Matrices
Indexing
Operators and functions Logical vectors/matrices

Relational and logical operators

Relational and logical functions
􏰁 logical(convertnumericalvaluestologicalvalues)
􏰁 true(logical1),false(logical0)
􏰁 true(n), false(n)(generatean×nmatrixoftrue/false values)
􏰁 any(trueifanyelementsarenon-zero),all(trueifall elements are non-zero)
􏰁 ischar,isinteger,islogical(trueifallelementsareof the same type char\integer\logical)
􏰁 isequal(A, B) (true if the matrices A and B have the same size and contain the same values)
􏰁 isfinite,isinf(trueifallelementsarefinite/infinite-Inf)
􏰁 isnan(trueifallelementsarenotdefined-nan)
􏰁 isreal

Logical vectors
􏰁 Usingrelationaloperatorsonavectorormatrixresultsinalogical vector or matrix
» v = [-2 10 nan 30 -11 Inf 31];
» positive = (v >= 0)
positive =
0101011 » all(positive)
ans = 0
» any(positive)
ans =
1
» positive_finite = (v >= 0) & (isfinite(v))
positive_finite =
0101001
»v(2,:) =[10-4-81502-Inf]; »v>0
ans =
0101011 1001010

Logical indexing
􏰁 Logicalvectors/matricescanbeusedasindexestoextractthevalues that meet certain conditions
» v = [-2 10 nan 30 -11 Inf 31; 10 -4 -8 15 0 2 -Inf] v=
-2 10 nan 30 -11 Inf 31
10 -4 -8 15 0 2 -Inf
» positive_finite = (v > 0) & (isfinite(v));
» v(positive_finite)
ans =
10 10 30 15 2 31
􏰁 Alogicalindexcanbeconstructedfromavectorof0and1.
» a = [1 2 3 4 5 6 7 8];
» index = logical([0 1 1 0 0 1 1 0]);
» a(index) % the numerical vector and the logical vector
MUST have the same size !
ans =
2367

Logical indexing: Example
􏰁 Example:takesquare-rootsoftheabsolutevalues,butpreserve the signs
» A = [36 -4 9; 16 9 -25] A=
36-4 9
16 9 -25 » B = A;
» k = (B>=0) k=
101
110
» B(k) = sqrt(B(k));
» B(~k) = -sqrt(-B(~k)) B=
6 -2 3 4 3 -5
% ~1 = 0, ~0 = 1

find :Examples
􏰁 find(X)returnsavectorcontainingthelinearindicesofeachnonzero element in array X.
» v = [-2 10 nan 30 -11 Inf 31];
» positive = v > 0;
» v(positive) % the elements of v which are positive ans =
10 30 Inf 31
» find(positive) % the index of the positive elements of v ans =
2467
= [ 3 7 1 10; 4 9 10 -2];
= find(X == 10, 1); % find the linear index of the first element of X equal
= find(X == 10) % find the linear index of all elements of X equal 10
6
7
»[i, j] = find(X == 10); % find the subscripted indexes of all elements of X equal 10
» [i j]
ans =
23
14
» X(find(X > 4))
ans =
7 9 10 10
» X
» k 10
» k ans =

find :Examples

To remember …
􏰁 BewareofCommonPitfalls
􏰁 Attempting to create a matrix that does not have the same number of values in each row
􏰁 Attempting to use an array of double 1s and 0s to index into an array (must be logical, instead)
􏰁 Confusing matrix multiplication (the inner dimensions must agree) and array multiplication (element by element, so the same size).
􏰁 ProgrammingStyleGuidelines
􏰁 If possible, try not to extend vectors or matrices, as it is not very efficient
􏰁 To be general, never assume that the dimensions of any array (vector or matrix) are known. Instead, use the function length or numel to determine the number of elements in a vector, and the function size for a matrix:
len = length(v);
[r, c] = size(A);