How to write the function to create a diagonal matrix from upper right to lower left in R?

  • A+
Category:Languages

I would like to write one function whose input is a square matrix, and it returns a square matrix whose numbers from the upper right corner down to lower left corner are preserved and other numbers are zero.

For example suppose A is a 4*4 matrix in the following.(sorry I do not know how to type the matrix expression)

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

How can I write a function in R without any loops to transform the matrix into this?

[0,0,0,4] [0,0,7,0] [0,10,0,0] [13,0,0,0] 

 


This feels like a gymnastics exercise...

xy <- matrix(1:16, ncol = 4, byrow = TRUE)  xy <- apply(xy, MARGIN = 1, rev)  xy[lower.tri(xy)] <- 0 xy[upper.tri(xy)] <- 0  t(apply(xy, MARGIN = 1, rev))       [,1] [,2] [,3] [,4] [1,]    0    0    0    4 [2,]    0    0    7    0 [3,]    0   10    0    0 [4,]   13    0    0    0 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: