Matrix in R Explained – All about matrix in R

Matrix in R:

In this tutorial we will learn about matrix in R. All columns in a matrix must have the same mode(numeric, character, etc.) and the same length. The general format of matrix in R is

mymatrix <- matrix(vectornrow=rncol=cbyrow=FALSE)

byrow=TRUE indicates that the matrix should be filled by rows. byrow=FALSE indicates that the matrix should be filled by columns (the default).

mymatrix <- matrix(c(1,2,3,5,6,7,9,10,12), nrow=3, ncol=3, byrow=FALSE)
mymatrix

 

output:

      [,1]    [,2]    [,3]

[1,]    1    5    9

[2,]    2    6   10

[3,]    3    7   12

 

 

Accessing Elements of a Matrix in R:

Elements of a matrix can be accessed by using the row and column index of the element.

# Access the element at 3rd column and 1st row.
print(mymatrix[1,3])

# Access the element at 2nd column and 3rd row.
print(mymatrix [3,2])

# Access only the  2nd row.
print(mymatrix [2,])

# Access only the 3rd column.
print(mymatrix [,3])

 

When we execute the above code, it produces the following result −

[1] 9

[1] 7

[1]  2  6 10

[1]  9 10 12

 

Matrix Computations in R (Matrix addition, Matrix subtraction, Matrix multiplication, Matrix division):

Various mathematical operations are performed on the matrices using the R operators. The result of the operation is also a matrix.

Prerequisite is both the matrices has to be of same dimension

matrix1 <- matrix(c(1, 3, 5, 7), nrow = 2)
matrix2 <- matrix(c(2, 4, 6, 8), nrow = 2)

# Add the matrices.
Mat.Add <- matrix1   matrix2

# Subtract the matrices
Mat.Sub <- matrix1 - matrix2

# Multiply the matrices.
Mat.Multi <- matrix1 * matrix2

# Divide the matrices
Mat.Div <- matrix1 / matrix2

When we execute the above code, it produces the following result

Result of Matrix Addition in R:

      [,1]    [,2]

[1,]    3   11

[2,]    7   15

 

Result of Matrix Subtraction in R

      [,1]    [,2]

[1,]   -1   -1

[2,]   -1   -1

 

Result of Matrix Multiplication in R

      [,1]    [,2]

[1,]    2   30

[2,]   12   56

 

Result of Matrix Division in R

      [,1]    [,2]

[1,] 0.50 0.8333333

[2,] 0.75 0.8750000

previous-small matrix in R

next_small matrix in R