MATLAB Matrix and Operations


foreword

Compared with other languages, MATLAB is very powerful in processing matrices and vectors. The following mainly records the operations of some matrices during the learning process.


First, the creation of the matrix

1.1 Matrix creation :
Enclose the elements of the matrix in square brackets, and enter the elements in the order of the matrix rows; the
elements in the same row are separated by commas or spaces , and the rows are separated by semicolons or enter keys

For example:

>> a=[1, 2, 3; 4, 5, 6; 7, 8, 9]  %矩阵创建
a =

     1     2     3
     4     5     6
     7     8     9
     
>> a=[1, 2, 3]  %行向量

a =

     1     2     3

>> a=[1; 2; 3]  %列向量

a =

     1
     2
     3

1.2 Creation of equally spaced row vectors:

Row vectors play an important role in drawing images, expression operations, etc.

1) colon expression

格式1  x1:dx:x2
格式2  x1:x2

Explanation:
The initial value x1, increment dx and final value x2 represent the start value, step size and end value respectively.
Increment can be a negative value, if omitted, the default increment is 1;
when the increment is omitted or the increment > 0 and the initial value > the final value, it is an empty vector;
when the increment < 0 and the initial value < the final value, it is also empty vector.

2) Use linspace to generate equally spaced row vectors

The format of the linspace function: linspace(a,b,n)


Explanation: The function of the linspace function is to generate a row vector of n elements at equal intervals from a to b (n is 100 by default)

. The use of the two creation methods depends on the situation. If you need to control the number of vectors, It is more convenient to use the linspace function. If you need to control the step size of a range, it is faster to use the colon expression.

The two creation methods are as follows:

t1=0:0.1:pi;
t2=linspace(0,2*pi,5);

1.3 Using Matlab internal functions to generate special matrices

In the elmat function library of MATLAB there are some functions for creating special matrices

function name function function
zeros Create zero matrix
ones Create all ones matrix
eye Create the identity matrix
rand Generate random numbers uniformly distributed between [0, 1]
randn Generates random numbers that follow a standard normal distribution (mean zero, standard deviation 1)

The calling format and usage of the function are as follows:

zeros(n) produces an n×n matrix of zeros
zeros(m,n) produces an mxn matrix of zeros
zeros(size(A)) produces a zero matrix of the same size as matrix A
t = rand Generate a random number uniformly distributed between [0, 1]
t = rand(3) Generate a 3x3 random number matrix with elements evenly distributed between [0, 1]
t=rand(3,4) Generate a 3x4 matrix of random numbers uniformly distributed between [0, 1]
t=10*rand(3,4)-5 Generate a 3x4 random matrix uniformly distributed between [-5,5]
t=randn(3,4)*sqrt(5)+3 Generate a 3x4 random matrix with a normal distribution with a mean of 3 and a variance of 5

Second, the basic operation of the matrix

1. Access to matrix elements

1) Access to vector elements:
Let v be a vector, then v(i) represents the ith element of vector v.
Note: Array subscripts start from 1 in Matlab.

2) Matrix element access——full subscript mode
A(i,j) indicates the element in row i and column j in matrix A.
For example:
A=[1, 2, 3; 4, 5, 6; 7, 8, 9]
A( 1, 2 ) is 2

3) The single subscript method
can also refer to the matrix elements according to the storage order (serial number) of the matrix elements in the memory

Note: In Matlab, the matrix is ​​written in the order of rows, but in memory, it is stored in the order of columns!

4) Logical subscript method (see sub-array fetching)

2. Take the sub-array

Similar to accessing elements in a matrix, the operation of taking out a sub-array in a matrix is ​​roughly the same

1) Full subscript method

Format: A(Rows, Cols)

The result is a sub-matrix, where
Rows is a vector consisting of row subscripts (of the row to be taken) (if only 1 row is taken, Rows is a scalar)
Cols is a column subscript of the column to be taken The composed vector (if only one column is taken, Cols is a scalar)
":" appearing in the position of the row subscript means all rows,
":" appears in the position of the column subscript means all columns,
end appears in the position of the row subscript means the largest The row subscript,
end appears in the position of the column subscript to indicate the largest column subscript

For example:

>>A=[1 2 3 4;5 6 7 8;9 10 11 12];
A(1,:)     %表示提取A的第1A(:,end)   %表示提取A的最后1A([3  1], :)  %表示提取A的第3行和第1行(行的顺序和A([1 3],:)不同

2) Single subscript method:
Generally speaking, it is to take out multiple elements in the form of vectors

Format: A(S), the result is a vector composed of (some or all) elements in A

where S is a vector consisting of single subscripts of these elements.
For example:

>>A=[1 2 3 4;5 6 7 8;9 10 11 12];
>>A(1:6)
ans =

     1     5     9     2     6    10

3) Logical expression
1. Use the find function

Basic format: indexes=find(X)

Function: Return the serial number (single subscript) of the non-zero element in the array X, if there is no non-zero element, return an empty array

Format: [I, J]=find(X), X is a matrix

Function: Return the row number and column number of the non-zero elements in matrix X.

Format: [I, J, V]=find(X), X is a matrix

Function: Return the row number, column number and value of the non-zero elements in the matrix X

2. Logical arrays as subscripts

The operation results of relational expressions and logical expressions are logical arrays, and logical functions can also be used to convert numerical arrays into logical arrays

Format: logical(X)

Function: Convert the numeric array X to a logical array

This method of taking an array is usually used to filter out special elements in the array.
For example:

It is known that A=[4,-5,0,0,4; -5,0,7,-6,0], find out the positive and even numbers in the elements of A, count the number, and sum.

Method 1: Use the find() function

A=[4,-5,0,0,4;  -5,0,7,-6,0]
xp=find(A>0 & rem(A,2)==0)   %A中正偶数的序号
yp=A(xp)                     %A中的正偶数
N=length(xp)                 % A中正偶数的个数
sum(yp)                      %A中正偶数之和 

Method 2: Use logical array subscripts

A=[4,-5,0,0,4;  -5,0,7,-6,0]
Lp =  A>0 & rem(A,2)==0
yp=A(Lp)    %A中的正偶数,也可直接写成yp=A(A>0 & rem(A,2)==0)
N=length(yp)
sum(yp)

3. Matrix element assignment

After learning how to access sub-arrays and matrix elements, matrix assignment becomes very simple
1) Full subscript method

Format: A(Rows, Cols)=B

Function: assign some elements of the matrix A.
Among them, Rows and Cols are both scalars or vectors, respectively specifying the row and column where the element to be assigned is located.
When B is a scalar, it means that the specified elements of A are assigned to B;
when B is not a scalar, the number of rows and columns of matrix B must be exactly the same as the number of rows and columns of the left sub-matrix. Special attention should be paid to
A = B means that the assigned A becomes a scalar

2) Single subscript mode:

Format: A(Indexes) = B

Function: Assign values ​​to some elements of the matrix A.
Among them, Indexes is a scalar or vector (used to specify the serial number of the element to be assigned).
Note: When A is a matrix, its single subscript (serial number) cannot exceed the
boundary. When B is a scalar, it means Assign the specified elements of A to B;
when B is not a scalar, the number of elements in B must be equal to the number of elements to be assigned in A (but the number of rows and columns may not be equal)

4. Matrix splicing and expansion

Matrix splicing:
put several matrices in [ ], and
separate horizontal connections with spaces or commas,

[AB] or [A , B] can also be written as horzcat(A,B)

Vertical links are separated by semicolons or carriage returns,

[A ; B] can also be written as vertcat(A,B)

Matrix extension:
function repmat

Format: repmat(A, row,col) or repmat(A, [row,col])

Function: Repeat matrix A row and col times along the direction of row and column respectively
For example: repmat(A , 2 , 3) ​​is the same as [AAA ; AAA]

5. Deletion of matrix elements

Deleting matrix elements is very simple. Only by assigning a value to empty ([]), you can delete several row elements, several column elements and the entire array

3. Arithmetic operations on matrices

The usage of operators and special symbols in Matlab can be viewed by using the help ops command

1. Basic matrix operations

add C=A+B C=plus(A,B)
reduce C=A-B C=minus(A,B)
accumulate C=+A C=uplus(A)
accumulative C=-A C=uminus(A)
product C=A*B C=mtimes(A,B)
power A^k mpower(A,k)
left division A\B = inv(A)*B mldivide(A,B)
right division A/B = A*inv(B) mrdivide(A,B)
conjugate transpose A’ ctranspose(A)
non-conjugate transpose A.’ transpose(A)

Appeal calculation formula, when A is a scalar, the scalar is operated with each element of the matrix, otherwise, it obeys the algorithm of linear algebra

What needs special attention is that the left division operation
x=A \ b is the solution of the linear equation system A*x = b
. That is, if you want to solve the linear equation system,
insert image description hereyou only need the following code to achieve:

A=[2 2 -1 1;4 3 -1 2;8 3 -3 4;3 3 -2 -2];
b=[4 6 12 6]';
x=A\b %等价于 x=inv(A)*b 

2. Vector (array) operations

Add a . in front of the operator * \ / ^ to indicate array operations (or dot operations)

A.*B times(A,B)
C=A.\B C=ldivide(A,B) , after execution C(i,j) = B (i,j) \ A(i,j)
C=A./B C=rdivide(A,B) , after execution C(i,j) = B (i,j) / A(i,j)
A.^B power(A,B)

4. Relational logic operations of matrices

1. Relational operators

There are six relational operators in MATLAB:
==(eq), ~= (ne), < (lt), <= (le), > (gt), >= (ge) Relational algorithm:

1
) When two When the first comparison quantity is a scalar quantity, the magnitude of the two numbers is directly compared. If the relationship is established, the result of the relational expression is 1, otherwise it is 0.
2) When the quantities involved in the comparison are two matrices of the same type, the comparison is performed on the elements at the same position of the two matrices one by one according to the scalar relationship operation rules, and the element comparison result is given. The result of the final relational operation is a matrix with the same dimension as the original matrix, and its elements are composed of 0 or 1.
3) When one of the comparisons is a scalar and the other is a matrix, compare each element of the scalar and the matrix one by one according to the scalar relationship operation rules, and give the element comparison result. The result of the final relational operation is a matrix with the same dimension as the original matrix, and its elements are composed of 0 or 1.

2. Logical operators

a&b When both a and b are non-zero, the result of the operation is 1; as long as one of a and b is zero, the result is 0.
a|b As long as one of a and b is non-zero, the result is 1 (only when a and b are both zero, the operation result is 0, otherwise it is 1)
~a When a is zero, the result of the operation is 1; when a is non-zero, the result of the operation is 0
xor(a,b) When exactly one of a and b is 0 and the other is not 0, the result of the operation is 1, otherwise it is 0
a && b (predetermined AND) When a is 0, the result is 0, and the value of the expression on the right side of && is not calculated (only when the left side of the logical operator is non-zero, the operation on the right side of the symbol continues).
a || b (prerequisite or) When a is 1, the result is 1, without calculation

(1)若参与逻辑运算的是两个同型矩阵,则对两个矩阵相同位置的元素逐对按标量规则进行逻辑运算。 最终运算结果是一个与原矩阵同型的逻辑矩阵。
(2)若参与逻辑运算的一个是标量,一个是矩阵,则分别用矩阵的每个元素和标量进行逻辑运算。最终运算结果是一个与原矩阵同型的逻辑矩阵。
(3) 逻辑非是一个单目运算。若A是一个数组,~A 对矩阵A的每个元素进行逻辑非运算,得到的结果是一个与A同型的逻辑矩阵。

五、矩阵相关函数

矩阵分析

函数 功能
inv(A) 方阵A的逆
pinv(A) 矩阵A 的广义逆(或称为伪逆)
det(A) 方阵A的行列式.
rank(A) 矩阵的秩
trace(A) 矩阵A的迹 (即主对角线元素之和 ).
poly (A) 当A是方阵时,求矩阵A的特征多项式
fliplr 用于将矩阵各列左右颠倒,
flipud 将矩阵各行上下颠倒,
rot90 将矩阵元素绕矩阵的中心逆时针旋转90度
flipdim(A,dim) 功能:将A关于第d维翻转得到B。dim=1, 对行下标进行反转; dim=2, 对列下标进行反转
any(x) 功能:1)若x是一个向量,如果x中存在非零元素,则返回1;否则,返回0。2)若x为矩阵,则分别对矩阵的每一列进行判断,最后返回一个由元素0和1组成的行向量。
all(x) 功能:(1)若x是一个向量,如果x中所有元素都非0,则返回1;否则,返回0 (2)若x为矩阵,则分别对矩阵的每一列进行判断,最后返回一个由元素0和1组成的行向量。
isempty(A) 判断A是否为空矩阵,如果是返回1,否则返回0.
isnan(A) 对于A的每个元素分别判断是否为NaN
isinf(A) 对于A的每个元素分别判断是否为无穷大(inf或者-inf)
isfinite(A) 对于A的每个元素分别判断是否为有限的值
isa(x, ‘ClassName’) 判断x是否为’ClassName’类型的数据(常量或变量),例如:isa(x,’double’)判断x是否为双精度型的变量,isnumeric(A) 判断A是否为数值型,islogical(A) 判断A是否为逻辑型,类似的还有:isfloat(A), isinteger(A),isreal(A) ,ischar(A), iscell(A), isstruct(A)等
isscalar(A) 判断A是否为标量
isvector(A) 判断A是否为向量
isrow(A) 判断A是否为行向量
iscolumn(A) 判断A是否为列向量
isequal(A,B) 如果A和B是同型的,并且数组的元素也相同,则返回1,否则返回0
exist 判断是否存在指定的变量或者文件

矩阵运算

函数 功能
expm 矩阵指数运算
logm 矩阵指数运算
sqrtm 矩阵开方运算
funm 调用函数,例如:funm(A,’exp’)或funm(A, @exp)等价于expm(A) ;funm(A,’log’) 等价于 logm(A) ; funm(A,’sqrt’) 等价于sqrtm(A)

线性代数

函数 功能
Z=null(A) Z的各列为矩阵A零空间的一组标准正交基,即:A*Z=0, Z’*Z=I 且size(Z,2)=dim(null(A)),可用于求Ax=0的基础解系
B=orth(A) 得到range(A)的一组标准正交基,即B’*B=I, 并且B和A张成相同的线性空间
rref(A) 利用高斯消元法产生矩阵A的行阶梯形矩阵(即矩阵非零行的第1个非零元素为1,且该非零元素所在列的其它元素均为零,可用于求Ax=b的解或通解)
subspace(A,B) 用于求两个子空间之间的夹角

矩阵的范数与条件数

函数 功能
norm - 求矩阵或向量的范数
normest - 估计矩阵的2范数.
normest1 - 估计矩阵的1范数.
cond - 求矩阵的条件数
rcond - 估计1范数下的条件数的倒数
condest - 估计1范数下的条件数
condeig - 计算矩阵特征值的条件数

矩阵分解

函数 功能
chol - Cholesky分解.
cholinc - Incomplete Cholesky decomposition.
ldl - Block LDL' decomposition.
lu - LU decomposition.
away - Incomplete LU decomposition.
qr - QR decomposition

Eigenvalues ​​and Singular Value Decomposition

function Function
eig - Eigenvalue decomposition, computing eigenvalue problems and generalized eigenvalue problems.
svd - Singular value decomposition
gsvd - Generalized singular value decomposition
eigs - Calculate the largest (or smallest) k eigenvalues ​​and the corresponding eigenvectors (can also be used to find generalized eigenvalue problems).
svds - Compute the largest (or smallest) k singular values

Summarize

MATLAB is a powerful software. The operation of matrix is ​​very important for learning this language. It took a day to sort out the relevant content and write this blog. Generally speaking, it is boring and cumbersome, but writing After finishing, you will feel a sense of accomplishment and master the knowledge more proficiently. I hope that the future learning path will be smoother.

Guess you like

Origin blog.csdn.net/qq_49288154/article/details/122208093