# [R] anti off diagonal min max mean - how to rotate matrix by 90 degree

Marc Schwartz marc_schwartz at me.com
Wed Jul 17 22:38:47 CEST 2013

```On Jul 17, 2013, at 3:04 PM, Witold E Wolski <wewolski at gmail.com> wrote:

> How can id do this efficiently in R ?
>
> 1 0 0
> 0 2 0
> 0 0 3
>
>
> rotate right
> 0 0 1
> 0 2 0
> 3 0 0
> rotate left
> 0 0 3
> 0 2 0
> 1 0 0
>
> What I want to do is described here:
> http://stackoverflow.com/questions/13049575/r-min-max-and-mean-of-off-diagonal-elements-in-a-matrix
>
> but I want do to it for all off-anti-diagonals.
>
> I am also concerned that the method described on stackoverflow isn't
> necessarily efficient.
> I work with matrices of size 3k * 3k.
>

I did not take the time to review in detail the solutions on SO, but here is one approach for rotation, albeit, not fully tested:

> mat
[,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    2    0
[3,]    0    0    3

# Rotate right
> t(mat)[, ncol(mat):1]
[,1] [,2] [,3]
[1,]    0    0    1
[2,]    0    2    0
[3,]    3    0    0

# Rotate left
> t(mat)[nrow(mat):1, ]
[,1] [,2] [,3]
[1,]    0    0    3
[2,]    0    2    0
[3,]    1    0    0

big.mat <- matrix(rep(0, 3000 * 3000), ncol = 3000)

> str(big.mat)
num [1:3000, 1:3000] 0 0 0 0 0 0 0 0 0 0 ...

> system.time(mat.right <- t(big.mat)[, ncol(big.mat):1])
user  system elapsed
0.273   0.000   0.273

> system.time(mat.left <- t(big.mat)[nrow(big.mat):1], )
user  system elapsed
0.094   0.000   0.099

Regards,

Marc Schwartz

```