How do I convert a n*1 matrix to a n*n diagonal matrix

后端 未结 3 1128
梦如初夏
梦如初夏 2021-01-19 11:04

I have a nx1 matrix I want to convert this to a nxn diagonal matrix in R

\"matrix

相关标签:
3条回答
  • 2021-01-19 11:28

    In your case, where the original vector contains identical elements, it suffices to multiply the n x n Identity matrix by 0.25 as the comments suggested.

    But the general case of a vector with non-identical elements is more interesting:

    Denote your n x 1 column vector by v = (v_1,...,v_n)'. Then, define the n x n matrix E_i as a matrix having 1 in its [i,i] element and zeros everywhere else. Also define the n x 1 column vector e_i as a vector having 1 in the [i] position (row) and zeros everywhere else.

    Then the n x n matrix V = diag(v_1,...,v_n) can be obtained as

    V = Σ(E_i v e_i')

    where the sum is over i=1,...n

    0 讨论(0)
  • 2021-01-19 11:29

    As @Ben Bolker has suggested, you can simply define your identity matrix using diag:

    my.matrix <- diag(0.25, 4)
    my.matrix
    ##      [,1] [,2] [,3] [,4]
    ## [1,] 0.25 0.00 0.00 0.00
    ## [2,] 0.00 0.25 0.00 0.00
    ## [3,] 0.00 0.00 0.25 0.00
    ## [4,] 0.00 0.00 0.00 0.25
    
    0 讨论(0)
  • 2021-01-19 11:35

    If you just want to know how to do this in R, it's:

    my.matrix       <- matrix(0, nrow=4, ncol=4)
    diag(my.matrix) <- rep(0.25, 4)
    
    0 讨论(0)
提交回复
热议问题