在R中创建身份矩阵 [英] Creating Identity Matrices in R

查看:75
本文介绍了在R中创建身份矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建不同大小的身份矩阵,并且可以像这样在较小的规模上做到这一点:

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

就像这样:

> 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.

是否有更简单的方法来创建 n 个值身份矩阵?

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

推荐答案

指定nrowx是长度为1的向量时,diag的一种(两种)用途矩阵

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)

或者您可以创建一个0s矩阵并填写对角线:

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)

所有这些都给我:

#      [,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

这篇关于在R中创建身份矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆