Skip to content

Instantly share code, notes, and snippets.

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

Flip a matrix

Amat is the input matrix.

Flip horizontally

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

Flip vertically

Bmat = Amat
for(i in 1:ncol(Amat)) Bmat[,i] = Amat[,ncol(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

Flip horizontally

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

Output:

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

Flip vertically

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

Output:

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