当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


R语言 diag()用法及代码示例


R语言中的diag()函数用于构造对角矩阵。

用法: diag(x, nrow, ncol)

参数:
x:值作为诊断元素出现。
nrow, ncol:表示元素的行数和列数。

范例1:


# R program to illustrate
# diag function
  
# Calling the diag() function with 
# some number which will act as
# rows as well as columns number
diag(3)
diag(5)

输出:

     [, 1] [, 2] [, 3]
[1, ]    1    0    0
[2, ]    0    1    0
[3, ]    0    0    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

范例2:


# R program to illustrate
# diag function
  
# Calling the diag() function
diag(5, 2, 3)
diag(10, 3, 3)

输出:

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

     [, 1] [, 2] [, 3]
[1, ]   10    0    0
[2, ]    0   10    0
[3, ]    0    0   10

相关用法


注:本文由纯净天空筛选整理自Kanchan_Ray大神的英文原创作品 Construct a Diagonal Matrix in R Programming – diag() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。