w3resource

Rotate a Given Matrix 90 Degrees Clockwise in R Programming

R Programming: Matrix Exercise-12 with Solution

Write a R program to rotate a given matrix 90 degree clockwise rotation.

Sample Solution:

R Programming Code:

# Create a 3x3 matrix with values from 1 to 9
x = matrix(1:9, 3)

# Print the original matrix
print("Original matrix:")
print(x)

# Rotate the matrix 90 degrees clockwise
# Step 1: Reverse the elements of each column using 'rev'
# Step 2: Apply the reverse operation to each column with 'apply'
# Step 3: Transpose the resulting matrix using 't'
rotate = t(apply(x, 2, rev))

# Print the rotated matrix
print("Rotate the said matrix 90 degree clockwise:")
print(rotate)

Output:

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

Explanation:

  • Create a Matrix:
    • x = matrix(1:9, 3)
      • Creates a 3x3 matrix with values from 1 to 9. The matrix is filled by column by default.
  • Print the Original Matrix:
    • print("Original matrix:")
      • Prints the label "Original matrix:".
    • print(x)
      • Prints the contents of the matrix x.
  • Rotate the Matrix 90 Degrees Clockwise:
    • rotate = t(apply(x, 2, rev))
      • apply(x, 2, rev):
        • Applies the rev function to each column (2 indicates column-wise operation) of the matrix x. This reverses the order of elements in each column.
      • t(...):
        • Transposes the matrix resulting from the apply function, effectively rotating the original matrix 90 degrees clockwise.
  • Print the Rotated Matrix:
    • print("Rotate the said matrix 90 degree clockwise:")
      • Prints the label "Rotate the said matrix 90 degree clockwise:".
    • print(rotate)
      • Prints the contents of the rotated matrix.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a R program to find row and column index of maximum and minimum value in a given matrix.
Next: Write a R program to concatenate two given matrixes of same column but different rows.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/r-programming-exercises/matrix/r-programming-matrix-exercise-12.php