R中矩阵的逆
矩阵的逆只是矩阵的倒数,就像我们在普通算术中对单个数字所做的那样,该数字用于求解方程以找到未知变量的值。矩阵的逆矩阵是与原始矩阵相乘时将作为单位矩阵的矩阵。
在处理线性代数表达式时,求矩阵的逆是最常见的任务之一。我们只能找到那些方阵且行列式非零的矩阵的逆矩阵。
Note: Ensure that the matrix is non-singular that is the determinant should not be 0.
矩阵方程:
where,
A^-1 is the inverse of matrix A.
x is the unknown variable column.
B is the solution matrix.
矩阵逆方程:
有两种方法可以找到矩阵的逆:
- 使用solve()函数:
solve()
是 R 中的通用内置函数,有助于求解以下线性代数方程,如上图所示。它既可以应用于向量,也可以应用于矩阵。# R program to find inverse of a Matrix # Create 3 different vectors # using combine method. a1 <- c(3, 2, 5) a2 <- c(2, 3, 2) a3 <- c(5, 2, 4) # bind the three vectors into a matrix # using rbind() which is basically # row-wise binding. A <- rbind(a1, a2, a3) # print the original matrix print(A) # Use the solve() function # to calculate the inverse. T1 <- solve(A) # print the inverse of the matrix. print(T1)
输出:
[,1] [,2] [,3] a1 3 2 5 a2 2 3 2 a3 5 2 4 a1 a2 a3 [1,] -0.29629630 -0.07407407 0.4074074 [2,] -0.07407407 0.48148148 -0.1481481 [3,] 0.40740741 -0.14814815 -0.1851852
- 使用 inv()函数:
inv()
函数是 R 中的内置函数,专门用于求矩阵的逆矩阵。Note:Ensure that you have installed the ‘matlib’ package in your environment.
寻找矩阵的行列式:
# Create 3 different vectors. a1 <- c(3, 2, 8) a2 <- c(6, 3, 2) a3 <- c(5, 2, 4) # Bind the 3 matrices row-wise # using the rbind() function. A <- rbind(a1, a2, a3) # determinant of matrix print(det(A))
输出:
-28
求矩阵的逆:
# find inverse using the inv() function. print(inv(t(A)))
输出:
[1,] -0.2857143 0.5 0.1071429 [2,] -0.2857143 1.0 -0.1428571 [3,] 0.7142857 -1.5 0.1071429