- A+

Category：Languages

I have a set of vectors, and would like to stack them on top of each other to create diagonal entries to a matrix.

What would be an easy way to create the example_out matrix from c1 and c2?

`c1 <- seq(1, 4) c2 <- seq(5, 8) example_out <- matrix(c(1,0,0,0,5,2,0,0,0,6,3,0,0,0,7,4,0,0,0,8), nrow=5, byrow=T) example_out `

Create a matrix out of `0`

s, then fill main diagonal with `c1`

and sub diagonal with `c2`

.

`example_out <- matrix(rep(0, 20), 5, 4) diag(example_out) <- c1 diag(example_out[-1, ]) <- c2 `

*Yielding*

`> example_out [,1] [,2] [,3] [,4] [1,] 1 0 0 0 [2,] 5 2 0 0 [3,] 0 6 3 0 [4,] 0 0 7 4 [5,] 0 0 0 8 `

*Data*

`c1 <- seq(1, 4) c2 <- seq(5, 8) `