从矩阵中获取所有对角向量 [英] Get all diagonal vectors from matrix
问题描述
我想弄清楚如何获得矩阵的所有对角线.例如,假设我有以下矩阵:一个 <- 矩阵(1:16,4)
I'm trying to figure out how to get all the diagonals of a matrix. For example, say I have the following matrix: A <- matrix(1:16,4)
使用diag(A)
函数会返回
[1] 1 6 11 16
除了主对角线之外,我还想列出它上方和下方的所有对角线.
In addition to the primary diagonal, I would like a list of all the diagonals above and below it.
5 10 15
2 7 12
9 14
3 8
4
13
我找到了以下链接 https://stackoverflow.com/a/13049722,它给了我正上方和正下方的对角线主要的,但是我似乎无法弄清楚如何扩展代码以获取任何大小矩阵的其余部分.我尝试了两个嵌套的 for 循环,因为似乎矩阵下标的某种递增会产生我正在寻找的结果.我尝试在 for 循环中使用 ncol(A)、nrow(A),但似乎无法找出正确的组合.另外我知道在 R 中通常不赞成 for 循环.
I found the following link https://stackoverflow.com/a/13049722 which gives me the diagonals directly above and below the primary one, however I cannot seem to figure out how to extend the code to get the rest of them for any size matrix. I tried two nested for loops since it appears that some kind of incrementing of the matrix subscripts would produce the result I am looking for. I tried using ncol(A), nrow(A) in the for loops, but couldn't seem to figure out the right combination. Plus I am aware that for loops are generally frowned upon in R.
给出的代码是:
diag(A[-4,-1])
diag(A[-1,-4])
返回两条对角线,包括上下
which returned the two diagonals, both upper and lower
当然,这是一个方阵,并不是我想要执行的所有矩阵都是方阵.如有必要,用 NA 填充非方形区域是可以接受的.我需要的答案可能在页面上的其他答案之一中,但最初的问题涉及手段、总和等,这增加了一层超出我想要做的复杂性.我有一种感觉,这个问题的解决方案会非常简单,但我没有遇到过.我也很惊讶我无法在 SO 上的任何地方找到这个问题,这似乎是一个足够常见的问题.也许我不知道这个问题的正确术语.
Of course this is a square matrix and not all of the matrices I want to perform this on will be square. Filling in the non-square area with NAs would be acceptable if necessary. The answer I need may be in one of the other answers on the page, but the original question involved means, sums, etc. which added a layer of complexity beyond what I am trying to do. I have a feeling the solution to this will be ridiculously simple, but it just isn't occurring to me. I'm also surprised I was not able to find this question anywhere on SO, it would seem to be a common enough question. Maybe I don't know the proper terminology for this problem.
推荐答案
A <- matrix(1:16, 4)
# create an indicator for all diagonals in the matrix
d <- row(A) - col(A)
# use split to group on these values
split(A, d)
#
# $`-3`
# [1] 13
#
# $`-2`
# [1] 9 14
#
# $`-1`
# [1] 5 10 15
#
# $`0`
# [1] 1 6 11 16
#
# $`1`
# [1] 2 7 12
#
# $`2`
# [1] 3 8
#
# $`3`
# [1] 4
这篇关于从矩阵中获取所有对角向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!