#Foundation and Application of Econometrics, Spring 2015, Pepared by Dr. I-Ming Chiu
#Accompany 368_Handout02.pdf
#We learn how to conduct matrix operations in R. Important matrix functions (i.e., commands) will be thoroughly explained in this document.
#Later I'll show that why matrix operations can be a powerful mathematical tool to manipulate data & conduct statistical analysis.
# (1) Create a matrix
# Command to create a matrix: matrix(Arg. 1, Arg. 2, Arg. 3).
#Argument 1: the elements in the matrix; “c(2,-3,1,-1,1,2)”.
#Argument 2: number of rows; “nrow = 2”.
#Argument 3: number of columns; “ncol = 3”.
A = matrix(c(2,-3,1,-1,1,2),nrow=3,ncol=2)
#Notice:
#1. By default, the elements enter into a matrix in columns. If you want the elements to be entered in rows, the argument is byrow = “TRUE” (or “T”). Insert this statement in-between 1st and 2nd argument.
#2. After you get familiar with R, you can drop “nrow” and “ncol” arguments.
#3. When there is no confusion, “nrow” or “ncol” alone should be enough to identify the size (dimension) of a matrix.
#(2) Take vector(s) or element(s) out of a matrix
row1_A = A[1,]
col2_A = A[,2]
A[2,2]
A[3,2]
# (3) Multiplication by a scalar
3*A
#(4) Matrix Addition and Subtraction
B = matrix(c(1,4,-2,1,2,1),3)
A + B
A - B
# (5) Matrix Multiplication
C = matrix(c(1,2,0,-1,3,2),2)
A%*%C
C%*%A
D = matrix(c(2,1,3),1)
D%*%A
A%*%D #Does this operation work? Why or Why not?
#(6) Transpose of a Matrix
t(A)
t(t(A))
#(7) Special Matrices
#Identity Matrix
I3 = diag(c(1,1,1))
#Symmetric Matrix
E = matrix(c(2,1,5,1,3,4,5,4,-2),3)
t(E)
E ==t(E)
#(8) Determinant of a matrix
det(E)
#(9) Inverse of a matrix
solve(E)
E%*%solve(E) #Why is the outcome of this operation not an "exact" Identity matrix?
#solve simultaneous linear equation system
rm(list=ls())
A = matrix(c(3, 1, 2, -1), 2)
b = matrix(c(0, -2), 2, 1)
(X = solve(A)%*%b)
#Solve the supply-demand model example by yourself as a practice
#(10) Dimension of a matrix
> dim(A)
[1] 3 2
> dim(E)
[1] 3 3
> nrow(A)
[1] 3
> ncol(A)
[1] 2
#(11) Computing column and row sums
A
colSums(A)
rowSums(A)
sum(A)
#(12) Computing column and row means
rowMeans(A)
colMeans(A)
mean(A)
#(13) Horizontal & Vertical Concatenation
A
B
cbind(A,B)
rbind(A,B)
#(14) Take out (Replace) a single element, one column (row) vector and n column (rows) of vectors from a matrix
E = matrix(1:24,6)
E
E[3,2]
E[2,]
E[,4]
E[4:6,2:4]
E[-1,]
E[-1:-2,]
E[3:4,2:3]
E[1,] = 1
E
E[2,2] = 0
E
#(15) We'll deal with eigenvalue problems later when it's needed