如何在 R 中求矩阵的逆矩阵
使用求解函数,可以在 R 中计算矩阵的逆矩阵。大多数不经常使用 R 的人误以为可以使用 inv 函数来实现此目的,但 base R 中没有名为 inv 的函数来求矩阵的逆矩阵。
示例
考虑以下矩阵及其逆矩阵 −
> M1<-1:4 > M1<-matrix(1:4,nrow=2) > M1 [,1] [,2] [1,] 1 3 [2,] 2 4 > solve(M1) [,1] [,2] [1,] -2 1.5 [2,] 1 -0.5 > M2<-matrix(1:4,nrow=2,byrow=TRUE) > M2 [,1] [,2] [1,] 1 2 [2,] 3 4 > solve(M2) [,1] [,2] [1,] -2.0 1.0 [2,] 1.5 -0.5 > M3<-matrix(c(12,14,16,18,20,22,24,26,28,30,32,34),nrow=3) > M3 [,1] [,2] [,3] [,4] [1,] 12 18 24 30 [2,] 14 20 26 32 [3,] 16 22 28 34 > solve(M3) Error in solve.default(M3) : 'a' (3 x 4) must be square
此处,求解函数给出了错误,因为无法计算非正方形矩阵的逆矩阵。
> M4<-matrix(c(12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42),nrow=4) > M4 [,1] [,2] [,3] [,4] [1,] 12 20 28 36 [2,] 14 22 30 38 [3,] 16 24 32 40 [4,] 18 26 34 42 > solve(M4) Error in solve.default(M4) : Lapack routine dgesv: system is exactly singular: U[3,3] = 0
此输出显示错误,因为矩阵 M4 的逆矩阵不存在,尽管它是一个正方形矩阵,但有时即使正方形矩阵的逆矩阵也不存在。
我们来看一些具有逆矩阵的高维矩阵 −
> M5<-matrix(c(1,8,4,2,4,5,5,1,2,2,5,4,4,1,1,2),nrow=4) > M5 [,1] [,2] [,3] [,4] [1,] 1 4 2 4 [2,] 8 5 2 1 [3,] 4 5 5 1 [4,] 2 1 4 2 > solve(M5) [,1] [,2] [,3] [,4] [1,] -0.07086614 0.17322835 -0.1417323 0.1259843 [2,] 0.11023622 -0.04724409 0.2204724 -0.3070866 [3,] -0.09448819 -0.10236220 0.1443570 0.1679790 [4,] 0.20472441 0.05511811 -0.2572178 0.1916010 > M6<-matrix(c(2,3,5,4,7,4,5,6,5,2,1,4,5,6,6,2,5,5,4,5,4,7,5,7,3),ncol=5) > M6 [,1] [,2] [,3] [,4] [,5] [1,] 2 4 1 2 4 [2,] 3 5 4 5 7 [3,] 5 6 5 5 5 [4,] 4 5 6 4 7 [5,] 7 2 6 5 3 > solve(M6) [,1] [,2] [,3] [,4] [,5] [1,] 5.000000e-01 -0.24000000 -0.2200000 1.194481e-16 0.260000000 [2,] 1.457168e-16 -0.20000000 0.4000000 -8.500145e-17 -0.200000000 [3,] -4.285714e-01 -0.12571429 0.1942857 2.857143e-01 -0.125714286 [4,] -3.571429e-01 0.50857143 0.1685714 -4.285714e-01 0.008571429 [5,] 2.857143e-01 0.09714286 -0.4228571 1.428571e-01 0.097142857
广告