R Program to rotate a given matrix 90 degree clockwise rotation


April 1, 2022, Learn eTutorial
1430

How to rotate a given matrix 90-degree clockwise rotation

To write an R program for rotating a matrix, we are using the matrix() built-in function. The matrix() function is an in-built fiction in R that will create a matrix from the given set of values. The syntax of the function is,

matrix(data = NA, nrow = 4, ncol = 6, dimnames = NULL)

  • NA: An optional data vector.
  • nrow: number of rows needed
  • ncol: The number of columns needed.
  • byrow: it fills the matrix by rows if this value is false then the matrix is filled by columns.
  • dimnames: NULL or a list of length 2 giving the row and column names respectively.

How to implement matrix rotation in the R Program

In this R program, we directly give the values to the built-in function for creating a matrix and then use t(apply()) for rotating it. Finally, print the function result.

Here we use variables Matx for assigning a matrix with values 1 to 9. Rotate the matrix by calling like t(apply(Matx, 2, rev)). Here the apply() returns a vector or array obtained by applying a function to an array or matrix. The function t() helps to get the transpose of the given matrix of the data frame.

ALGORITHM

STEP 1: Assign variable Matx with matrix values

STEP 2: Create a matrix of 1 to 9 elements with 3 rows

STEP 3: Rotate it by calling like  t(apply(Matx, 2, rev))

STEP 4: Assign the result into a variable final

STEP 5: print the result matrix final

 

R Source Code

                                          Matx=  matrix(1:9, 3)
print("Original matrix:")
print(Matx)
final = t(apply(Matx, 2, rev))
print("Rotate the matrix 90 degree clockwise:")
print(final)
                                      

OUTPUT

[1] "Original matrix:"
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
[1] "Rotate the matrix 90 degree clockwise:"
     [,1] [,2] [,3]
[1,]    3    2    1
[2,]    6    5    4
[3,]    9    8    7