4

Consider the following column vector:

vec <- rbind(c(0.5),c(0.6))

I want to convert it into the following 4x4 diagonal matrix:

0.5   0   0    0 
  0 0.6   0    0 
  0   0 0.5    0
  0   0   0  0.6

I know I can do it by the following code:

dia <- diag(c(vec,vec))

But what if I want to convert it into a 1000x1000 diagonal matrix. Then the code above is so efficient. Maybe I can use rep, but I am not totally sure how to do it. How can I do it more efficient?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Michael
  • 565
  • 4
  • 11

2 Answers2

2

Here is one other way using recycling:

diag(c(vec), length(vec)*2)
Clemsang
  • 5,053
  • 3
  • 23
  • 41
1

I think your approach is already good enough, here is another way by initialising the matrix and using rep to fill diagonals.

n <- 4
mat <- matrix(0, ncol = n, nrow = n)
diag(mat) <- rep(vec, n/2)

mat
#     [,1] [,2] [,3] [,4]
#[1,]  0.5  0.0  0.0  0.0
#[2,]  0.0  0.6  0.0  0.0
#[3,]  0.0  0.0  0.5  0.0
#[4,]  0.0  0.0  0.0  0.6

and following your approach you could do

diag(rep(vec, n/2))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213