Matrix Operations in R
Matrix Operations in R
OPERATIONS
ADDITION AND SUBTRACTION
• The most basic matrix operations are addition and subtraction. In the following examples
we are going to use the square matrices of the following block of code
• A <- matrix(c(10, 8, 5, 12), ncol = 2, byrow = TRUE)
• A
• To find the transpose of a matrix in R you just need to use the t function as follows:
• t(A)
• [, 1] [, 2]
• [1, ] 10 5
• [2, ] 8 12
MATRIX MULTIPLICATION IN R
• Multiplication by a scalar
• In order to multiply or divide a matrix by a scalar you can make use of the * or /
operators, respectively:
• 2*A
• [, 1] [, 2]
• [1, ] 20 16
• [2, ] 10 24
• A/2
• [, 1] [, 2]
• [1, ] 5.0 4
• [2, ] 2.5 6
ELEMENT-WISE MULTIPLICATION
• The element-wise multiplication of two matrices of the same dimensions can also be
computed with the * operator. The output will be a matrix of the same dimensions of the
original matrices.
• A*B
• [, 1] [, 2]
• [1, ] 50 24
• [2, ] 75 72
MATRIX MULTIPLICATION
• Power of A
• There is no a built-in function in base R to
calculate the power of a matrix, so we will • [, 1] [, 2]
• On the one hand, you can make use of the %^ • On the other hand the matrixcalc package provides the
matrix.power function:
% operator of the expm package as follows:
• # install.packages("matrixcalc")
• # install.packages("expm")
• library(matrixcalc)
• library(expm)
• matrix.power(A, 2)
• A %^% 2
• You can check that the power is correct with the following
code: A %*% A
SOLVE FUNCTION
• R programming has a dedicated function to do the task for you. The solve() function in R
programming takes a matrix as an argument and then returns the inverse of that matrix.
THE CBIND() AND RBIND() FUNCTION IN R
•
• The cbind() function in R is a function that allows you to create or modify the matrices. The
function either takes vectors or matrices as an input and then combines those as columns to create
a new matrix. If the matrices are provided as an argument, it concatenates the two matrices
column-wise.
•
• On the similar lines the rbind() function in R allows you to create or modify the matrices. It either
takes vectors or matrices as an input and then combines those as rows to create a new matrix. If the
matrices are provided as an input, this function concatenates them row-wise.