将nx1矩阵转换为方形对角矩阵

时间:2015-08-13 06:36:46

标签: r matrix

我有一个矩阵10x1矩阵a如下:

      [,1]
 [1,]    0
 [2,]  133
 [3,]  206
 [4,]  104
 [5,]  159
 [6,]    0
 [7,]   89
 [8,]  134
 [9,]    0
[10,]  119

我试图将其转换为10x10对角矩阵,如下所示:

      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    1    0    0    0    0    0    0    0    0     0
 [2,]    0    133  0    0    0    0    0    0    0     0
 [3,]    0    0    206  0    0    0    0    0    0     0
 [4,]    0    0    0    104  0    0    0    0    0     0
 [5,]    0    0    0    0    159  0    0    0    0     0
 [6,]    0    0    0    0    0    0    0    0    0     0
 [7,]    0    0    0    0    0    0    89   0    0     0
 [8,]    0    0    0    0    0    0    0    134  0     0
 [9,]    0    0    0    0    0    0    0    0    0     0
[10,]    0    0    0    0    0    0    0    0    0     119

我尝试了一些基本的方法,例如diag(a, 10, 10)没有任何效果,没有任何想法,任何帮助都非常感谢。

1 个答案:

答案 0 :(得分:2)

简短回答:

diag(as.vector(a))