Bsc R programming Notes by Divyansh Tripathi
# Define two 2x2 matrices
A <- matrix(c(1, 2, 3, 4), nrow = 2)
B <- matrix(c(5, 6, 7, 8), nrow = 2)
# Add matrices A and B
C <- A + B
print(C)
output:
[,1] [,2]
[1,] 6 10
[2,] 8 12
# Define two 2x2 matrices
A <- matrix(c(5, 6, 7, 8), nrow = 2)
B <- matrix(c(1, 2, 3, 4), nrow = 2)
# Subtract matrix B from matrix A
C <- A - B
print(C)
output:
[,1] [,2]
[1,] 4 4
[2,] 4 4
# Define two compatible matrices
A <- matrix(c(1, 2, 3, 4), nrow = 2) # 2x2
B <- matrix(c(5, 6, 7, 8), nrow = 2) # 2x2
# Multiply matrices A and B
C <- A %*% B
print(C)
output:
[,1] [,2]
[1,] 19 22
[2,] 43 50
Matrix Inversion
The inverse of a matrix AAA is another matrix A−1A^{-1}A−1 such that A×A−1=IA \times A^{-1} =
IA×A−1=I, where III is the identity matrix. Not all matrices have inverses; only square matrices with a
non-zero determinant are invertible.
Using the solve() Function
# Define a square matrix
A <- matrix(c(4, 7, 2, 6), nrow = 2)
# Compute the inverse of matrix A
A_inv <- solve(A)
print(A_inv)
output:
[,1] [,2]
[1,] 0.6 -0.7
[2,] -0.2 0.4
Verification
# Multiply A and its inverse
I <- A %*% A_inv
print(I)
[,1] [,2]
[1,] 1 0
[2,] 0 1
This confirms that A×A−1=IA \times A^{-1} = IA×A−1=I.