Skip to content

Instantly share code, notes, and snippets.

@nilforooshan
Last active March 30, 2019 09:55
Show Gist options
  • Save nilforooshan/4f589e369bc251ed782ca2cb67100318 to your computer and use it in GitHub Desktop.
Save nilforooshan/4f589e369bc251ed782ca2cb67100318 to your computer and use it in GitHub Desktop.
R: Rotate matrix

Rotate a matrix -90/90 degrees

Amat is the input matrix.

Rotate 90 degrees

Bmat = t(Amat)
for(i in 1:nrow(t(Amat))) Bmat[i,] = t(Amat)[nrow(t(Amat))+1-i,]

Rotate -90 degrees

Bmat = t(Amat)
for(i in 1:ncol(t(Amat))) Bmat[,i] = t(Amat)[,ncol(t(Amat))+1-i]

Example:

(Amat = matrix(1:15, nrow=3))

Input:

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    4    7   10   13
[2,]    2    5    8   11   14
[3,]    3    6    9   12   15

Rotate 90 degrees

Bmat = t(Amat)
for(i in 1:nrow(t(Amat))) Bmat[i,] = t(Amat)[nrow(t(Amat))+1-i,]
Bmat

Output:

     [,1] [,2] [,3]
[1,]   13   14   15
[2,]   10   11   12
[3,]    7    8    9
[4,]    4    5    6
[5,]    1    2    3

Rotate -90 degrees

Bmat = t(Amat)
for(i in 1:ncol(t(Amat))) Bmat[,i] = t(Amat)[,ncol(t(Amat))+1-i]
Bmat

Output:

     [,1] [,2] [,3]
[1,]    3    2    1
[2,]    6    5    4
[3,]    9    8    7
[4,]   12   11   10
[5,]   15   14   13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment