y=matrix(c(1,2,3,4),nrow=2,ncol=2) #R是按列储存的
y
y[,2]
#创建矩阵每个赋值
m=matrix(nrow = 2,ncol = 2)
m[1,1]=1
m[1,2]=3
m[2,1]=2
m[2,2]=4
m
matrix(c(1,2,3,4,5,6),nrow=2,byrow = T) #改成按行排列byrow
3.2一般矩阵运算
#3.2.1线性代数运算
y%*%y #矩阵乘法
3*y
y+y
#3.2.2矩阵索引
z=matrix(c(1,2,3,4,1,1,0,0,1,0,1,0),nrow=4)
z[,2:3]
z[2:3,] #提取行
z[2:3,2]
y=matrix(c(1,2,3,4,5,6),nrow = 3)
y
y[c(1,3),]=matrix(c(1,1,8,12),nrow = 2)
y
x=matrix(ncol=3,nrow=3)
y=matrix(c(4,5,2,3),nrow=2)
y
x[2:3,2:3]<-y #矩阵赋值
x
y
y[-2,]#取出第二行外的元素
#3.2.3扩展案例:图像操作
library(pixmap)
mtrush1=read.pnm("mtrush1.pgm")
mtrush1
plot(mtrush1)
str(mtrush1)
#pixmap属于S4类型
mtrush1@grey[28,88] #0.0表示黑色,1.0表示白色 中间值为灰色
#将罗斯福总统脸去掉
mtrush2=mtrush1
mtrush2@grey[84:163,135:177]=1
plot(mtrush2)
#将罗斯福总统脸某糊掉
# adds random noise to img, at the range rows,cols of img; img and the
# return value are both objects of class pixmap; the parameter q
# controls the weight of the noise, with the result being 1-q times the
# original image plus q times the random noise
blurpart <- function(img,rows,cols,q) {
lrows <- length(rows)
lcols <- length(cols)
newimg <- img
randomnoise <- matrix(nrow=lrows, ncol=lcols,runif(lrows*lcols))
newimg@grey[rows, cols] <- (1-q) * img@grey[rows, cols] + q * randomnoise
return(newimg)
}
mtrush3=blurpart(mtrush1,84:163,135:177,0.65)
plot(mtrush3)
#3.2.4矩阵元素筛选
x=matrix(c(1,2,3,4,1,1,0,0,1,0,1,0),ncol=2)
x
x[x[,2]>=1,]
j=x[,2]>=1
j
x[j,]
x=matrix(c(1,2,3,4,5,6),ncol=2)
z=c(5,12,13)
x[z%%2==1,]
x[x[,1]>1 & x[,2]>5,] #元素正确但是数据类型不对
x
#3.2.5扩展案例:生成协方差矩阵
makecov <- function(rho,n) {
m <- matrix(nrow=n,ncol=n)
m <- ifelse(row(m) == col(m),1,rho) #==是一个函数
return(m)
}
row(x)
makecov(0.2,3)
#3.4.1改变矩阵的大小
x=c(12,3,4,5,2,33)
c(x,20)
c(x[1:3],33,x[4:6])
x
x[-2:-4] #删除2-4的数
one=(c(1,1,1,1))
one
z=matrix(c(1:4,1,1,0,0,1,0,1,0),ncol=3)
z
cbind(one,z)
cbind(1,z)#循环补齐
cbind(c(1,2),c(3,4))#快速生成矩阵
#循环每次往矩阵添加一行和列做法不可取,最好开始定义一个空的大矩阵
m=matrix(1:6,nrow=3)
m[c(1,3),]
#3.4.2扩展案例:找到图中距离最近的一对端点
# returns the minimum value of d[i,j], i != j, and the row/col attaining
# that minimum, for square symmetric matrix d; no special policy on ties
mind <- function(d) {
n <- nrow(d)
# add a column to identify row number for apply()
dd <- cbind(d,1:n)
wmins <- apply(dd[-n,],1,imin)
# wmins will be 2xn, 1st row being indices and 2nd being values
i <- which.min(wmins[2,])
j <- wmins[1,i]
return(c(d[i,j],i,j))
}
# finds the location, value of the minimum in a row x
imin <- function(x) {
lx <- length(x)
i <- x[lx] # original row number
j <- which.min(x[(i+1):(lx-1)])
k <- i+j
return(c(k,x[k]))
}
3.5向量与矩阵的差异
z=matrix(1:8,nrow=4)
z
length(z) #矩阵就是一个向量
class(z)
attributes(z)
dim(z)
nrow(z)#对dim的简单封装
ncol(z)