## R Program to rotate a given matrix 90 degree clockwise rotation

### How to rotate a given matrix 90-degree clockwise rotation

Here we are explaining how to write an R program to rotate a given matrix 90-degree clockwise rotation. Here we are using a built-in function matrix() for this conversion. This method helps to creates a matrix from the given set of values. The syntax of this function is,

matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE,dimnames = NULL)
• NA: An optional data vector.
• nrow: The desired number of rows.
• ncol: The desired number of columns.
• byrow: If FALSE (the default) the matrix is filled by columns, otherwise filled by rows.
• dimnames: NULL or a list of length 2 giving the row and column names respectively.

### How to rotate a given matrix 90-degree clockwise rotation in the R Program

Below are the steps used in the R program to rotate a given matrix 90-degree clockwise rotation. In this R program, we directly give the values to built-in functions. And print the function result. Here we used variables Matx for assigning 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:")
##  "Original matrix:"
print(Matx)
##      [,1] [,2] [,3]
## [1,]    1    4    7
## [2,]    2    5    8
## [3,]    3    6    9
final = t(apply(Matx, 2, rev))
print("Rotate the matrix 90 degree clockwise:")
##  "Rotate the matrix 90 degree clockwise:"
print(final)
##      [,1] [,2] [,3]
## [1,]    3    2    1
## [2,]    6    5    4
## [3,]    9    8    7