我有一组向量,我想将它们堆叠在一起以创建矩阵的对角线条目。
从 c1 和 c2 创建 example_out 矩阵的简单方法是什么?
c1 <- seq(1, 4)
c2 <- seq(5, 8)
example_out <- matrix(c(1,0,0,0,5,2,0,0,0,6,3,0,0,0,7,4,0,0,0,8), nrow=5, byrow=T)
example_out
最佳答案
用 0
创建一个矩阵,然后用 c1
填充主对角线,用 c2
填充副对角线。
example_out <- matrix(rep(0, 20), 5, 4)
diag(example_out) <- c1
diag(example_out[-1, ]) <- c2
屈服
> example_out
[,1] [,2] [,3] [,4]
[1,] 1 0 0 0
[2,] 5 2 0 0
[3,] 0 6 3 0
[4,] 0 0 7 4
[5,] 0 0 0 8
数据
c1 <- seq(1, 4)
c2 <- seq(5, 8)
关于r - R中的 "diagonal"矩阵平方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51391117/