#####Chapter 1: Matrix Operations

###Section 1.2:  Matrix Multiplication
A <- matrix(c(10,3,4,5), nrow=2, ncol=2, byrow=TRUE)  
A  
B <- matrix(c(1,2,6,7), nrow=2, ncol=2, byrow=TRUE)    
B
AB <-A%*%B                       # %*% indicates matrix multiplication
AB

#Matrix transpose and sum of squares
A <- matrix(c(1,2,6,4,8,-4,5,6,5,4,2,3), nrow=4, ncol=3, byrow=TRUE)    
A
A.sq <-t(A)%*%A                  # t(A) indicates a transposed matrix
A.sq

#Create deviate scores and covariance matrix
N <-nrow(A)
D <-scale(A, center = TRUE, scale = FALSE)
covar <-(t(D)%*%D)/(N-1)
covar

#Create standardized scores and correlation matrix
Z <-scale(A, center = TRUE, scale = TRUE)
corr <-(t(Z)%*%Z)/(N-1)
corr

###Section 1.3: Determinants
A <- matrix(c(5,3,2,4), nrow=2, ncol=2, byrow=TRUE)    
det(A)   #R function for calculating the determinant

#Using Cramer's Rule to Solve Simultaneous Linear Equations
P <- matrix(c(5,7,8,4), nrow=2, ncol=2, byrow=TRUE) 
det.P <-det(P)
Px <- matrix(c(-11,7,4,4), nrow=2, ncol=2, byrow=TRUE) 
det.Px <-det(Px)
Py <- matrix(c(5,-11,8,4), nrow=2, ncol=2, byrow=TRUE) 
det.Py <-det(Py)
x=det.Px/det.P
y=det.Py/det.P
xy=c(x,y)
xy

#Minor and Cofactors Function
cofactor <- function(A) {
   n <- nrow(A)
    F <- matrix(NA, n, n)
     if(n>2){
        cofactors <- function(A, i, j) 
            (-1)^(i+j) * det( A[-i,-j] )
               for( i in 1:n )
                  for( j in 1:n )
                      F[i,j] <- cofactors(A, i, j)
F
}
     else{F<-matrix(c(A[4],-A[2],-A[3],A[1]),2,byrow=TRUE)}
F
}

A <- matrix(c(3,9,1,10,8,4,5,7,6), nrow=3, ncol=3, byrow=TRUE)
cofactor(A)

#Calculate Determinant from Cofactor Matrix
determ <-diag(A%*%t(cofactor(A)))
determ[1]

###Section 1.4:  Inverses
A <- matrix(c(10,3,4,5), nrow=2, ncol=2, byrow=TRUE);A 

#Create function to calculate adjugate
adjugate <- function(A) {
   n <- nrow(A)
   F <- matrix(NA, n, n)
    if(n>2){
      cofactors <- function(A, i, j) 
            (-1)^(i+j) * det( A[-i,-j] )
               for( i in 1:n )
                  for( j in 1:n )
                      F[i,j] <- cofactors(A, j, i)
                         F
}
    else{ F <-matrix(c(A[4],-A[3],-A[2],A[1]),2,byrow=TRUE)}
F
}
adjugate(A)
A.inv <-adjugate(A)/det(A);A.inv
RA.inv <-solve(A);RA.inv      #Rs solve command produces the inverse

#Use inverse to solve simultaneous equations with conformable matrices
X <- matrix(c(5,7,8,4), nrow=2, ncol=2, byrow=TRUE);X    
Y <-matrix(c(-11,4),nrow=2,ncol=1,byrow=TRUE);Y
B <-solve(X)%*%Y;B

#Use inverse to solve simultaneous equations with nonconformable matrices
X <- matrix(c(5,7,8,4,5,5), nrow=3, ncol=2, byrow=TRUE);X    
Y <-matrix(c(-11,4,-5),nrow=3,ncol=1,byrow=TRUE);Y
B <-solve(t(X)%*%X)%*%t(X)%*%Y;B
