1构造矩阵
> a=matrix(c(1,2,3,4),ncol=2,byrow=T)
> a
[,1] [,2]
[1,] 1 2
[2,] 3 4
> b=matrix(c(5,6,7,8),ncol=2,byrow=T)
> b
[,1] [,2]
[1,] 5 6
[2,] 7 8
2矩阵线性运算
> a+b
[,1] [,2]
[1,] 6 8
[2,] 10 12
> a-b
[,1] [,2]
[1,] -4 -4
[2,] -4 -4
> 2*a
[,1] [,2]
[1,] 2 4
[2,] 6 8
> a*b
[,1] [,2]
[1,] 5 12
[2,] 21 32
3矩阵乘法
> a%*%b
[,1] [,2]
[1,] 19 22
[2,] 43 50
4矩阵转置
> t(a)
[,1] [,2]
[1,] 1 3
[2,] 2 4
5取方阵的对角线元素
> diag(a);sum(diag(a))
[1] 1 4
[1] 5
> c=diag(c(1,2))
> c
[,1] [,2]
[1,] 1 0
[2,] 0 2
6矩阵求逆
> solve(a)
[,1] [,2]
[1,] -2.0 1.0
[2,] 1.5 -0.5
7矩阵的行列式
> det(a);det(b);det(c)
[1] -2
[1] -2
[1] 2