Storing the maximum values โ€‹โ€‹of diagonals in the matrix

Let's say I have a matrix A that represents the height values:

A = matrix(c(100,105,106,109,101,101,106,104,107,106,101,102,105,106,108,102,102,104,110,104),
           nrow=5, ncol=4)

      

I would like to create a new matrix that generated a diagonal analysis of matrix A. Starting with. in the top left corner I want to analyze each diagonal and store the maximum values โ€‹โ€‹step by step. The expected results should be as follows:

B = matrix(c(100,105,106,109,101,101,106,105,107,109,101,102,106,106,108,102,102,102,110,106),
           nrow=5, ncol=4)

      

Can anyone help me?

+3


source to share


1 answer


If I understand you correctly, you need the cumulative maximum for each diagonal. With cummax

and two for-loops, you can get what you want:

A[row(A)==col(A)] <- cummax(A[row(A)==col(A)])

for(i in 1:(nrow(A)-1)) {
  A[row(A)==col(A)-i] <- cummax(A[row(A)==col(A)-i])
}

for(i in 1:(ncol(A)-1)) {
  A[row(A)-i==col(A)] <- cummax(A[row(A)-i==col(A)])
}

      

The matrix now A

looks like this:

> A
     [,1] [,2] [,3] [,4]
[1,]  100  101  101  102
[2,]  105  106  102  102
[3,]  106  105  106  104
[4,]  109  107  106  110
[5,]  101  109  108  106

      


You can also wrap this in a function if you need this routine more often:

diagcummax <- function(m) {
  m[row(m)==col(m)] <- cummax(m[row(m)==col(m)])

  for(i in 1:(nrow(m)-1)) {
    m[row(m)==col(m)-i] <- cummax(m[row(m)==col(m)-i])
  }

  for(i in 1:(ncol(m)-1)) {
    m[row(m)-i==col(m)] <- cummax(m[row(m)-i==col(m)])
  }
  m
}

      

Then you just need to do:

diagcummax(A)

      



to get the desired result.


If you want to go from the top-right corner and then down-left, you need to enable rev

at some points the functions:

diagcummax.upright <- function(m) {
  m[row(m)==rev(col(m))] <- rev(cummax(rev(m[row(m)==rev(col(m))])))

  for(i in 1:(nrow(m)-1)) {
    m[row(m)==rev(col(m))-i] <- rev(cummax(rev(m[row(m)==rev(col(m))-i])))
  }

  for(i in 1:(ncol(m)-1)) {
    m[row(m)-i==rev(col(m))] <- rev(cummax(rev(m[row(m)-i==rev(col(m))])))
  }
  m
}

      

Now using

diagcummax.upright(A)

      

the following matrix is โ€‹โ€‹returned:

     [,1] [,2] [,3] [,4]
[1,]  100  101  101  102
[2,]  105  106  102  102
[3,]  106  104  105  104
[4,]  109  107  106  110
[5,]  107  106  110  104

      

+2


source







All Articles