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
极客教程