Skip to content

Instantly share code, notes, and snippets.

@nilforooshan
Last active October 2, 2024 21:22
Show Gist options
  • Select an option

  • Save nilforooshan/f07cb0cb8cee43897b32a2e79167ae2d to your computer and use it in GitHub Desktop.

Select an option

Save nilforooshan/f07cb0cb8cee43897b32a2e79167ae2d to your computer and use it in GitHub Desktop.
R: Flip a matrix

Flip a matrix

Example:

(Amat = matrix(1:15, nrow=3))
     [,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
     [,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
     [,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