2

I have a vector where the order of the elements are important, say

x <- c(1,2,3,4)

I would like to arrange my vector into a lower triangular matrix with a specific order where each row contains the preceding element of the vector. My goal is to obtain the following matrix

lower_diag_matrix   
       [,1] [,2] [,3] [,4]
[1,]    4    0    0    0
[2,]    3    4    0    0
[3,]    2    3    4    0
[4,]    1    2    3    4

I know I can fill the lower triangular area using lower_diag_matrix[lower.tri(lower_diag_matrix,diag = T)]<-some_vector but I can't seem to figure out the arrangement of the vector used to fill the lower triangular area. In practice the numbers will be random, so I would need a generic way to fill the area.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
danluuu
  • 23
  • 5

1 Answers1

1

Here's one way:

x <- c(2, 4, 7)
M <- matrix(0, length(x), length(x))
M[lower.tri(M, diag = TRUE)] <- rev(x)[sequence(length(x):1)]
M
#      [,1] [,2] [,3]
# [1,]    7    0    0
# [2,]    4    7    0
# [3,]    2    4    7
Julius Vainora
  • 47,421
  • 9
  • 90
  • 102