Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
例如,我有两个尺寸为 1x5 的矩阵,我想在执行c = a+b操作后将它们重塑为对称的 5x5 矩阵,然后添加diag(c) <- 1
c = a+b
diag(c) <- 1
比方说:
a <- matrix(seq(1,5), byrow = T) b <- matrix(seq(1,5), byrow = T)
我正在寻找的结果是:
1 3 4 5 6 3 1 5 6 7 4 5 1 7 8 5 6 7 1 9 6 7 8 9 1
请帮助,并提前谢谢你
我们可以outer用来做sum然后将对角线元素分配给1
outer
sum
out <- outer(a[,1], b[,1], FUN = `+`) diag(out) <- 1 out # [,1] [,2] [,3] [,4] [,5] #[1,] 1 3 4 5 6 #[2,] 3 1 5 6 7 #[3,] 4 5 1 7 8 #[4,] 5 6 7 1 9 #[5,] 6 7 8 9 1