################################################################### # MATRIX ALGEBRA IN R ################################################################### ######################################### #several ways to construct a matrix object ######################################### #create an empty matrix object A=matrix(NA,nrow=2,ncol=2) #Fill it with values #acces each position A[1,1]=2 A[1,2]=1 A[2,1]=3 A[2,2]=5 A[1,]=c(2,3) A[2,]=c(3,5) #or #this is a 2x2 matrix #so it has two columns and two rows #we can use cbind or rbind R commands to #bind two columns or two rows in a matrix respectivelly #create a vector with the first row R1=c(2,1) #create a vector with the second row R2=c(3,5) #use rbind to join the two rows into a matrix A.rbind=rbind(R1,R2) #if we use cbind on R1 and R2 then we will need to transpose #the matrix obtained as column bind of the two rows of A!!! cbind(R1,R2) A.cbind=t(cbind(R1,R2)) #Another way is just to simply turn a vector of all values into a matrix #ncol is number of columns A=matrix(c(2,1,3,5),ncol=2,byrow=TRUE) #be careful here with byrow = TRUE or FALSE, if it is TRUE # we will obtain the matrix A # if it is FALSE we will get transposed A transp.A=matrix(c(2,1,3,5),ncol=2) ################################## #matrix multiplication ################################## B=matrix(c(4,2,8,1),ncol=2,byrow=TRUE) #multiply matrices A and B using %*% D=A %*% B ################################## #NOTE: Do not use * for matrix multiplication #we can check what happens if we use * instead of %*% #when we want to multiply matrices: A*B #it returns a matrix where elements on a matching positions #in A and B are multiplied which is not a #matrix multiplication ################################## ################################## #matrix inversion ################################## A.inv=solve(A) #check if AxA.inv=I (identity matrix) I=A %*% A.inv ################################## #determinant ################################## A A.det=det(A) ######################################## #Markov Chain transition probability #matrix ######################################## P=matrix(c(0.3,0.7,0.4,0.6),ncol=2,byrow=T) #prob that it will rain two days from today P2=P%*%P #prob that it will rain four days from today P4=P2%*%P2 #prob that it will rain eight days from today P8=P4%*%P4 #Not much difference between P4 and P8 #limiting probability that the process will be in state #j after large number of transitions. #Note that this value is not dependent on the initial value anymore #pi_j=lim Pij^n, for n approaching inf