Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flip the matrix

Tags:

r

Hi everyone who loves while hates R:

Let's say you want to turn matrix M

      [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9

to N

       [,1] [,2] [,3]
[1,]    3    2    1
[2,]    6    5    4
[3,]    9    8    7

All you need to do is

N<-M[,c(3:1)]

And N's structure is still a matrix

However, when you want to turn matrix M

       [,1] [,2] [,3]
[1,]    1    2     3  

to N

       [,1] [,2] [,3]
[1,]    3    2     1  

if you do N<-M[,c(3:1)] R will give you

N
[1] 3 2 1

N now is a vector! Not a matrix!

My solution is N<-M%*%diag(3)[,c(3:1)] which needs big space to store the identity matrix however.

Any better idea?

like image 813
user2961927 Avatar asked Nov 06 '13 19:11

user2961927


People also ask

What does it mean to flip a matrix?

B = flip( A , dim ) reverses the order of the elements in A along dimension dim . For example, if A is a matrix, then flip(A,1) reverses the elements in each column, and flip(A,2) reverses the elements in each row.

Can you flip matrices?

To flip the matrix horizontally means that each row of the matrix is reversed. For example, flipping [1, 1, 0] horizontally results in [0, 1, 1]. To invert a matrix means that each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [0, 1, 1] results in [1, 0, 0].


2 Answers

You're looking for this:

N<-M[,c(3:1),drop = FALSE] 

Read ?Extract for more information. This is also a FAQ. This behavior is one of the most common debates folks have about the way things "should" be in R. My general impression is that many people agree that drop = FALSE might be a more sensible default, but that behavior is so old that changing it would be enormously disruptive to vast swaths of existing code.

like image 186
joran Avatar answered Sep 26 '22 12:09

joran


A=t(matrix(1:25,5,5))
B=matrix(0,5,5)
for(i in 1:5){
  B[i,(nrow(A)+1-i)]=1
}

A
# [,1] [,2] [,3] [,4] [,5]
# [1,]    1    2    3    4    5
# [2,]    6    7    8    9   10
# [3,]   11   12   13   14   15
# [4,]   16   17   18   19   20
# [5,]   21   22   23   24   25

A%*%B
# [,1] [,2] [,3] [,4] [,5]
# [1,]    5    4    3    2    1
# [2,]   10    9    8    7    6
# [3,]   15   14   13   12   11
# [4,]   20   19   18   17   16
# [5,]   25   24   23   22   21
like image 42
Tay Shin Avatar answered Sep 27 '22 12:09

Tay Shin