矩阵的逆可以借助solve函数在R中进行计算,大多数情况下,不使用R的人经常会错误地使用inv函数来实现此目的,但是在基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是平方矩阵,但不存在矩阵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