遍历矩阵的对角线+1 [英] Looping through diagonal+1 of a matrix
本文介绍了遍历矩阵的对角线+1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要遍历对角线+1(即对角线右边的1列的值)并将该值写入数据帧中的列:
I need to loop through the diagonal+1 (i.e. the values 1 column to the right of the diagonal) and write the value to a column in a dataframe:
write.csv(data.frame(matrix[1,2], matrix[2,3], matrix[3,4])
如何使用函数而不是仅列出值的所有位置来做到这一点?
How can I do this using a function, rather than just listing all the positions of the values?
推荐答案
您可以使用矩阵编制索引.
You can index using a matrix.
例如
m <- matrix(1:25, ncol = 5)
可以使用
offd <- cbind(1:4,2:5)
m[offd]
## [1] 6 12 18 24
您可以创建一个执行此操作的功能
You could create a function that does this
offdiag <- function(m, offset){
i <- seq_len(nrow(m)-offset)
j <- i + offset
m[cbind(i,j)]
}
offdiag(m, 1)
## [1] 6 12 18 24
offdiag(m, 2)
[1] 11 17 23
offdiag(m, 3)
## [1] 16 22
offdiag(m, 4)
## [1] 21
这篇关于遍历矩阵的对角线+1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文