R语言的一些矩阵运算
摘自:https://www.cnblogs.com/yupeter007/p/5325575.html
矩阵的存储默认是按列进行存储的
1,创建矩阵
matrix (data = NA, nrow = 1, ncol = 1, byrow =FALSE, dimnames = NULL)
创建一个c(1:12)的三行四列的矩阵,
colnames<-c("c1","c2","c3","c4")
rownames<-c("r1","r2","r3")
x<-matrix(1:12,nrow=3,ncol=4,byrow=TRUE,dimnames=list(rownames,colnames))
x
c1 c2 c3 c4
r1 1 2 3 4
r2 5 6 7 8
r3 9 10 11 12
2,矩阵的转置
y<-t(x)
若是针对的是一个向量
y<-(1:10)
装置后得到的是行向量
t(y)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 2 3 4 5 6 7 8 9 10
class(y)
[1] "integer"
class(t(y))
[1] "matrix"
若要的到列向量则
t(t(y))
[,1]
[1,] 1
[2,] 2
[3,] 3
[4,] 4
[5,] 5
[6,] 6
[7,] 7
[8,] 8
[9,] 9
[10,] 10
3,创建一个服从正态分布的随机数矩阵
matrix(rnorm(100),nrow=10)
4,制造一个数字相同的n列m行矩阵
matrix(2,ncol=n,nrow=m)
4.1创建对角矩阵
diag(x,ncol=n,nrow=m)
若x为矩阵 则diag(x)将会提取矩阵x的对角,则返回的是向量值
diag(x)
[1] 1 6 11
diag(diag(x))
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 6 0
[3,] 0 0 11
返回的是以矩阵对角的对角矩阵
diag(c(1:4),4,4)
[,1] [,2] [,3] [,4]
[1,] 1 0 0 0
[2,] 0 2 0 0
[3,] 0 0 3 0
[4,] 0 0 0 4
diag(3)
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1
A=diag(4)+1
A
[,1] [,2] [,3] [,4]
[1,] 2 1 1 1
[2,] 1 2 1 1
[3,] 1 1 2 1
[4,] 1 1 1 2
4,求矩阵的行数和列数
n<-ncol
m<-nrow
为矩阵的行和列命名
rownames(x)<-c()
colnames(x)<c()
5,矩阵运算
A为m×n矩阵,c>0,在R中求cA可用符号:“*”,例如:
c=2
c*A
[,1] [,2] [,3] [,4]
[1,] 2 8 14 20
[2,] 4 10 16 22
[3,] 6 12 18 24
6 矩阵相乘
A为m×n矩阵,B为n×k矩阵,在R中求AB可用符号:“%*%”,例如:
A=matrix(1:12,nrow=3,ncol=4)
B=matrix(1:12,nrow=4,ncol=3)
A%*%B
[,1] [,2] [,3]
[1,] 70 158 246
[2,] 80 184 288
[3,] 90 210 330
对矩阵求逆
方法一:直接用solve(x)
方法二:加载包MASS
library(MASS)
ginv(matrix)
7,向量和矩阵的内积和外积运算(向量的长度一样)
向量的内积
x<-c(1:5)
y<-c(3:7)
z<-crossprod(x,y)
z
[,1]
[1,] 85
向量的外积
w<-tcrossprod(x,y)
w
[,1] [,2] [,3] [,4] [,5]
[1,] 3 4 5 6 7
[2,] 6 8 10 12 14
[3,] 9 12 15 18 21
[4,] 12 16 20 24 28
[5,] 15 20 25 30 35
向量、矩阵的外积(叉积)
设x和y是n维向量,则x%o%y表示x与y作外积.
q<-x%o%y
q
[,1] [,2] [,3] [,4] [,5]
[1,] 3 4 5 6 7
[2,] 6 8 10 12 14
[3,] 9 12 15 18 21
[4,] 12 16 20 24 28
[5,] 15 20 25 30 35
a %o% b
, , 1, 1
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
, , 2, 1
[,1] [,2] [,3] [,4]
[1,] 2 8 14 20
[2,] 4 10 16 22
[3,] 6 12 18 24
, , 1, 2
[,1] [,2] [,3] [,4]
[1,] 3 12 21 30
[2,] 6 15 24 33
[3,] 9 18 27 36
, , 2, 2
[,1] [,2] [,3] [,4]
[1,] 4 16 28 40
[2,] 8 20 32 44
[3,] 12 24 36 48
outer()是更为强大的外积运算函数,outer(x,y)计算向量x与y的外积,它等价于x %o%y
函数。outer()的一般调用格式为
outer(x,y,fun=”*”)
det(x),求矩阵x的行列式值
qr(x)$rank求x矩阵的秩
解线性方程组和求矩阵的逆矩阵
若求解线性方程组Ax=b,其命令形式为solve(A,b),求矩阵A的逆,其命令形式为solve(A).设矩阵A=t(array(c(1:8,10),dim=c(3,3))),b<-c(1,1,1),则解方程组Ax=b的解x和求矩阵A的逆矩阵的命令如下:
<br>