我有以下矩阵(本身),我想找到它的对角线和它的反向对角线给出任何一点。我可以想到算法,但我不确定R函数将帮助我实现它。就像我知道如何访问穿过该点的所有行和cols所以我想也许找到对角线也是一种技巧。我想最终将每个对角线保存在向量中。
x = matrix(data=c(
"E","E","o","4","E","E","E",
"E","E","m","5","E","E","E",
"E","E","n","5","E","E","E",
"E","E","e","5","E","E","E",
"E","E","e","4","E","E","E",
"E","E","r","E","E","E","E"
), nrow=6, ncol=7, byrow=TRUE)
r=3
c=5
row=x[3,]
col=x[,5]
reverse_diagonal=x[i,j] in which (i+j==3+5)
diagonal=x[i,j] in which (i-j==3-5)
答案 0 :(得分:3)
对角线:
x[row(x) - col(x) == r - c]
# [1] "o" "5" "E" "E" "E"
反向对角线:
x[row(x) + col(x) == r + c]
# [1] "E" "e" "5" "E" "E" "E"
我建议您运行以下内容以了解其工作原理:
row(x)
col(x)
row(x) - col(x)
row(x) - col(x) == r - c
x[row(x) - col(x) == r - c]