> # MATRICES > > x<-c(1,3,2,10,5) #create a vector x with 5 components > y<-1:5 #create a vector of consecutive integers > x [1] 1 3 2 10 5 > y [1] 1 2 3 4 5 > m1<-cbind(x,y) #Column bind > m1 x y [1,] 1 1 [2,] 3 2 [3,] 2 3 [4,] 10 4 [5,] 5 5 > t(m1) # transpose of m1 [,1] [,2] [,3] [,4] [,5] x 1 3 2 10 5 y 1 2 3 4 5 > dim(m1) [1] 5 2 > m1<-rbind(x,y) # rbind() is for row bind and equivalent to t(cbind()). > m1 [,1] [,2] [,3] [,4] [,5] x 1 3 2 10 5 y 1 2 3 4 5 > > # LIST ELEMENTS AND SPECIFY MATRIX DIRECTLY (WITHOUT BINDING) > > m2<-matrix(c(1,3,2,5,-1,2,2,3,9),nrow=3) > m2 [,1] [,2] [,3] [1,] 1 5 2 [2,] 3 -1 3 [3,] 2 2 9 > > m2<-matrix(c(1,3,2,5,-1,2,2,3,9),ncol=3,byrow=T) # to fill row-wise > m2 [,1] [,2] [,3] [1,] 1 3 2 [2,] 5 -1 2 [3,] 2 3 9 > > m2[2,3] #element of m2 at the second row, third column [1] 2 > m2[2,] #second row [1] 5 -1 2 > m2[,3] #third column [1] 2 2 9 > m2[-1,] #submatrix of m2 without the first row [,1] [,2] [,3] [1,] 5 -1 2 [2,] 2 3 9 > m2[,-1] #without the first column [,1] [,2] [1,] 3 2 [2,] -1 2 [3,] 3 9 > m2[-1,-1] #submatrix of m2 with the first row and column removed [,1] [,2] [1,] -1 2 [2,] 3 9 > > # COMPONENT-WISE COMPUTATIONS > > m1<-matrix(1:4, ncol=2); m2<-matrix(c(10,20,30,40),ncol=2) > m1 [,1] [,2] [1,] 1 3 [2,] 2 4 > m2 [,1] [,2] [1,] 10 30 [2,] 20 40 > 2*m1 # scalar multiplication [,1] [,2] [1,] 2 6 [2,] 4 8 > m1+m2 # matrix addition [,1] [,2] [1,] 11 33 [2,] 22 44 > m1*m2 # component-wise multiplication [,1] [,2] [1,] 10 90 [2,] 40 160 > > # MATRIX OPERATIONS > > m1 %*% m2 # the usual matrix multiplication [,1] [,2] [1,] 70 150 [2,] 100 220 > solve(m1) #inverse matrix of m1 [,1] [,2] [1,] -2 1.5 [2,] 1 -0.5 > solve(m1)%*%m1 #check [,1] [,2] [1,] 1 0 [2,] 0 1 > diag(3) #diag() is used to construct a k by k identity matrix [,1] [,2] [,3] [1,] 1 0 0 [2,] 0 1 0 [3,] 0 0 1 > diag(c(2,3,3)) #as well as other diagonal matrices [,1] [,2] [,3] [1,] 2 0 0 [2,] 0 3 0 [3,] 0 0 3 > > # BE CAREFUL. R tries to read minds. > diag(m2) [1] 10 40 > > eigen(m2) # eigenvalues and eigenvectors of m2 $values [1] 53.722813 -3.722813 $vectors [,1] [,2] [1,] -0.5657675 -0.9093767 [2,] -0.8245648 0.4159736 > ev <- eigen(m2) # ev is a variable with two components > ev $values [1] 53.722813 -3.722813 $vectors [,1] [,2] [1,] -0.5657675 -0.9093767 [2,] -0.8245648 0.4159736 > ev$values # to extract components, use $ [1] 53.722813 -3.722813 > ev$vectors [,1] [,2] [1,] -0.5657675 -0.9093767 [2,] -0.8245648 0.4159736 > attach(ev) # to keep from typing ev > values [1] 53.722813 -3.722813 > vectors [,1] [,2] [1,] -0.5657675 -0.9093767 [2,] -0.8245648 0.4159736