3

I need to transform main diagonal

{matrix(
1 1 1 1,
0 2 2 2,
0 0 3 3,
0 0 0 4)
}

into:

{matrix(
0 0 0 1,
0 0 1 2,
0 1 2 3,
1 2 3 4)
}

I tried all operators I could find t(), arev(), flipud(), apply(x,2,rev) and so on. Without a positive result. Hope you can help me.

user20650
  • 24,654
  • 5
  • 56
  • 91
Nils
  • 173
  • 1
  • 1
  • 10
  • Could you for those less versed in these things explain in words how you go from input to output? – Heroka Dec 15 '15 at 13:38
  • 2
    `out <- matrix(0, ncol(m), nrow(m)) ; out[(col(out) + row(out)) > ncol(out)] <- m[upper.tri(m, TRUE)]` – user20650 Dec 15 '15 at 13:45
  • x=1:100 y=101:200 q=matrix(0, 100,101) q1=matrix(0, 100,101) for(i in 1:100) { q[i:100-i+1,i]=x[i:100] q1[1:i,i+1]=y[1:i] } better this way? – Nils Dec 15 '15 at 15:01
  • @Nils; i dont know... can you show it for the small example in your question please. [PS if it is an answer, and youre happy it works, you should feel free to write it up in the answer section] – user20650 Dec 15 '15 at 18:04

1 Answers1

0

Does this work for you? Takes each column and 'rotates' (for lack of a better word) x places, where x is the column index.

res <- sapply(1:ncol(input),function(x){
  #get relevant column
  base <- input[,x]
  n <- length(base)
  indices <- 1:n
  #reshuffle indices: first above x, then below x
  out <- base[c(indices[indices>x],indices[indices<=x])]
  out
})

all(res==output)
[1] TRUE

data used:

input <- structure(c(1, 0, 0, 0, 1, 2, 0, 0, 1, 2, 3, 0, 1, 2, 3, 4), .Dim = c(4L, 
4L))
output <- structure(c(0, 0, 0, 1, 0, 0, 1, 2, 0, 1, 2, 3, 1, 2, 3, 4), .Dim = c(4L, 
4L))
Heroka
  • 12,889
  • 1
  • 28
  • 38
  • thx, i could solve it an other way. is it possible to overwrite just parts of an matrix? `x=1:100 y=101:200 q=matrix(0, 100,101) q1=matrix(0, 100,101) for(i in 1:100) { q[i:100-i+1,i]=x[i:100] q1[1:i,i+1]=y[i:1] q2=flipud(q1) } for(j in 1:100) { q[100-j+1:100,j+1]=q2[100-j+1:100,j+1] }` – Nils Dec 15 '15 at 17:27