Question

I have the following matrix (per se) and I want to find its diagonal and its reverse diagonal given any point in it. I can think of the algorithm but I am not sure what R function will help me to implement it. Like I know how to access all the rows and cols crossing that point so I thought maybe there's a trick to finding the diagonals as well.I want to save each of the diagonals in a vector eventually.

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)
Was it helpful?

Solution

Diagonal:

x[row(x) - col(x) == r - c]
# [1] "o" "5" "E" "E" "E"

Reverse diagonal:

x[row(x) + col(x) == r + c]
# [1] "E" "e" "5" "E" "E" "E"

I suggest you run the following to understand how it works:

row(x)
col(x)
row(x) - col(x)
row(x) - col(x) == r - c
x[row(x) - col(x) == r - c]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top