Matrices

X<-matrix(1:12,nrow = 3,ncol = 4,byrow = TRUE)
Y<-matrix(1:12,nrow = 3,ncol = 4,byrow = FALSE)
print(X)
##      [,1] [,2] [,3] [,4]
## [1,]    1    2    3    4
## [2,]    5    6    7    8
## [3,]    9   10   11   12
print(Y)
##      [,1] [,2] [,3] [,4]
## [1,]    1    4    7   10
## [2,]    2    5    8   11
## [3,]    3    6    9   12

using rbind

rbind(1:4,5:8,c(9,10,11,12))
##      [,1] [,2] [,3] [,4]
## [1,]    1    2    3    4
## [2,]    5    6    7    8
## [3,]    9   10   11   12

using cbind

cbind(1:4,5:8,c(9,10,11,12))
##      [,1] [,2] [,3]
## [1,]    1    5    9
## [2,]    2    6   10
## [3,]    3    7   11
## [4,]    4    8   12

Dimensions

mat=matrix(1:9,nrow = 3,ncol = 3,byrow = T)
dim(mat)
## [1] 3 3
dmat<-matrix(data=1:9,nrow = 3,dimnames=list(c("A","B","C"),c("D","E","F")))
dmat
##   D E F
## A 1 4 7
## B 2 5 8
## C 3 6 9

Determinant

s<-matrix(data=c(4,2,3,1),nrow=2,byrow=T)
det(s) # Determinant
## [1] -2
diag(s) # Diagonal
## [1] 4 1
t(s)    #Transpose
##      [,1] [,2]
## [1,]    4    3
## [2,]    2    1
solve(s)# Inverse
##      [,1] [,2]
## [1,] -0.5    1
## [2,]  1.5   -2

Inverse of matrix

xs<-matrix(data<-c(4,3,3,4),nrow=2, byrow=T)
xs
##      [,1] [,2]
## [1,]    4    3
## [2,]    3    4
det(s)
## [1] -2
solve(s)
##      [,1] [,2]
## [1,] -0.5    1
## [2,]  1.5   -2

exercise

A<-matrix(data=c(4,2,3,1,7,8,3,2,4,9,1,5,3,8,1,6),nrow=4,byrow=T)
A
##      [,1] [,2] [,3] [,4]
## [1,]    4    2    3    1
## [2,]    7    8    3    2
## [3,]    4    9    1    5
## [4,]    3    8    1    6
t(A)
##      [,1] [,2] [,3] [,4]
## [1,]    4    7    4    3
## [2,]    2    8    9    8
## [3,]    3    3    1    1
## [4,]    1    2    5    6
solve(A)
##      [,1]  [,2] [,3]  [,4]
## [1,]  -16  19.5  -40  29.5
## [2,]    9 -11.0   23 -17.0
## [3,]   18 -21.5   44 -32.5
## [4,]   -7   8.5  -18  13.5
dim(A)
## [1] 4 4
diag(A)
## [1] 4 8 1 6
det(A)
## [1] 2

Rank of matrix

using the qr() for QR decomposition of a matrix rank of matrix can be obtained

sad<-matrix(data=c(1,3,9,2,4,0,3,9,27), nrow=3, byrow=T)
qr(sad)
## $qr
##            [,1]        [,2]          [,3]
## [1,] -3.7416574 -10.1559272 -2.405351e+01
## [2,]  0.5345225   1.6903085  1.521278e+01
## [3,]  0.8017837  -0.4001484  2.486900e-14
## 
## $rank
## [1] 2
## 
## $qraux
## [1] 1.267261e+00 1.916450e+00 2.486900e-14
## 
## $pivot
## [1] 1 2 3
## 
## attr(,"class")
## [1] "qr"

Matrix multiplication

%*% is used for matrix multiplication

AB<-matrix(data=c(64,30,18,61),nrow=2,byrow=T)
AB%*%AB
##      [,1] [,2]
## [1,] 4636 3750
## [2,] 2250 4261
solve(AB)
##              [,1]         [,2]
## [1,]  0.018133175 -0.008917955
## [2,] -0.005350773  0.019024970
AB%*%solve(AB)
##      [,1] [,2]
## [1,]    1    0
## [2,]    0    1