这部分,学过线性代数的可以复习一下,比较基础。笔记整理暂留。
3.1 Matrices and Vectors
Octave 代码:
% The ; denotes we are going back to a new row. A = [1, 2, 3; 4, 5, 6; 7, 8, 9; 10, 11, 12] % Initialize a vector v = [1;2;3] % Get the dimension of the matrix A where m = rows and n = columns [m,n] = size(A) % You could also store it this way dim_A = size(A) % Get the dimension of the vector v dim_v = size(v) % Now let's index into the 2nd row 3rd column of matrix A A_23 = A(2,3)
执行结果:
A =
1 2 3
4 5 6
7 8 9
10 11 12
v =
1
2
3
m = 4
n = 3
dim_A =
4 3
dim_v =
3 1
A_23 = 6
3.2 Addition and Scalar Multiplication
Octave 代码:
% Initialize matrix A and B A = [1, 2, 4; 5, 3, 2] B = [1, 3, 4; 1, 1, 1] % Initialize constant s s = 2 % See how element-wise addition works add_AB = A + B % See how element-wise subtraction works sub_AB = A - B % See how scalar multiplication works mult_As = A * s % Divide A by s div_As = A / s % What happens if we have a Matrix + scalar? add_As = A + s
执行结果:
A =
1 2 4
5 3 2
B =
1 3 4
1 1 1
s = 2
add_AB =
2 5 8
6 4 3
sub_AB =
0 -1 0
4 2 1
mult_As =
2 4 8
10 6 4
div_As =
0.50000 1.00000 2.00000
2.50000 1.50000 1.00000
add_As =
3 4 6
7 5 4
3.3 Matrix Vector Multiplication
Octave 代码:
% Initialize matrix A A = [1, 2, 3; 4, 5, 6;7, 8, 9] % Initialize vector v v = [1; 1; 1] % Multiply A * v Av = A * v
执行结果:
A =
1 2 3
4 5 6
7 8 9
v =
1
1
1
Av =
6
15
24
3.4 Matrix Matrix Multiplication
Octave 代码:
% Initialize a 3 by 2 matrix A = [1, 2; 3, 4;5, 6] % Initialize a 2 by 1 matrix B = [1; 2] % We expect a resulting matrix of (3 by 2)*(2 by 1) = (3 by 1) mult_AB = A*B % Make sure you understand why we got that result
执行结果:
A =
1 2
3 4
5 6
B =
1
2
mult_AB =
5
11
17
3.5 Matrix Multiplication Properties
Octave 代码:
% Initialize random matrices A and B A = [1,2;4,5] B = [1,1;0,2] % Initialize a 2 by 2 identity matrix I = eye(2) % The above notation is the same as I = [1,0;0,1] % What happens when we multiply I*A ? IA = I*A % How about A*I ? AI = A*I % Compute A*B AB = A*B % Is it equal to B*A? BA = B*A % Note that IA = AI but AB != BA
执行结果:
A =
1 2
4 5
B =
1 1
0 2
I =
Diagonal Matrix
1 0
0 1
IA =
1 2
4 5
AI =
1 2
4 5
AB =
1 5
4 14
BA =
5 7
8 10
3.6 Inverse and Transpose
Octave 代码:
% Initialize matrix A A = [1,2,0;0,5,6;7,0,9] % Transpose A A_trans = A' % Take the inverse of A A_inv = inv(A) % What is A^(-1)*A? A_invA = inv(A)*A
执行结果:
A =
1 2 0
0 5 6
7 0 9
A_trans =
1 0 7
2 5 0
0 6 9
A_inv =
0.348837 -0.139535 0.093023
0.325581 0.069767 -0.046512
-0.271318 0.108527 0.038760
A_invA =
1.00000 -0.00000 0.00000
0.00000 1.00000 -0.00000
-0.00000 0.00000 1.00000