#R example 2, 1/24/06
################-------vectors and operations-----
# 1) ----generate vectors--------------------
c(1,-2,1)
x=c(1,-2,1)
y=1:3
y
z<-seq(-3,2,length=6)
z
seq(-3,2,by=1)
seq(length=6, from=-3, by=1)
rep(0,3)
rep(y,2)
# 2) ----operators--- +,-,*,/ and ^(power)------
2*x+y
2*x+y+1
x*y # component-wise product, still a vector
x%*%y # inner product = sum(x*y)
x/y
x^2 # x*x
sqrt(sum(x*x)) # norm of x
########-------------matrices and operations------------
# 1)----generate matrix--------------------
matrix(1:12, nrow=3)
matrix(1:12, ncol=4)
matrix(1:12,2)
matrix(1:12,2,byrow=T)
T12=read.table("D://T1-2.DAT")
T12 #data.frame
scan("D://T1-2.DAT")
matrix(scan("D://T1-2.DAT"), ncol=3)
T12m=matrix(scan("D://T1-2.DAT"), ncol=3, byrow=T)
T12m #matrix
# 2)----matrix operation------------------
T12+T12
T12m+T12m
T12*T12 #component-wise square
T12%*%T12 #not data matrix
T12m%*%T12m #not conformable
T4141=T12m%*%t(T12m)
T33=t(T12m)%*%T12m
t33=crossprod(T12m) #crossprod(A, B)=A'B
T33
t33
# 3)----inverse matrix-------------------
solve(T33)%*%T33
# 4)----eigenvalue and eigenvector--------
eigen(T33)
eigen(T33, only.values=T)
vv=eigen(T33)
vv$values
vv$vectors
# 5)----spetral decomposition (singular-value decomposition)
svd(T33) #svd(A)gives eigenvalues d, orthogonal matrices u and v such that A=u%*%diag(d)%*%t(v)
SD=svd(T33)
SD$u%*%diag(SD$d)%*%t(SD$v)
T33
#singular value decomposition can also handler no square matrix
x=c(1, 3, 4, 5, 0, -2)
x=matrix(x,ncol=2,byrow=T)
x
svd(x)