Creating Identity Matrices in R

◇◆丶佛笑我妖孽 提交于 2020-01-02 00:53:25

问题


I'd like to create identity matrices of different sizes, and I'm able to do so on a smaller scale like so:

> x <- matrix(cbind(c(1,0), c(0,1)), 2)
> x
     [,1] [,2]
[1,]    1    0
[2,]    0    1

And like so:

> y <- matrix(cbind(c(1,0,0), c(0,1,0), c(0,0,1)), 3)
> y
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    0
[3,]    0    0    1

However, it seems this will become increasingly tedious as identity matrices increase in size.

Is there an easier way to create n-value identity matrices?


回答1:


one (two) of the uses for diag when nrow is specified or when x is a vector of length one, you get an identity matrix

diag(5)
diag(nrow = 5)

or you could create a matrix of 0s and fill in the diagonal:

mat <- matrix(0, 5, 5)
diag(mat) <- 1

## or shorter:
`diag<-`(matrix(0, 5, 5), 1)

All of these give me:

#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    0    0    0    0
# [2,]    0    1    0    0    0
# [3,]    0    0    1    0    0
# [4,]    0    0    0    1    0
# [5,]    0    0    0    0    1


来源:https://stackoverflow.com/questions/27094402/creating-identity-matrices-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!