I have an R matrix with nonnegative numeric values. The matrix is effectively a 2D height map, and I want to find all the local maxima in this matrix. For "flat" peaks, where neighboring elements are equal to each other (and they are collectively a local maximum), I don't care what happens as long as I get at least one coordinate within each "flat" region.
Are there any functions to do this efficiently? Obviously I could write the loop manually to go through and test every element individually, but doing that in R would be quite slow. I need to do this for around a million matrices, with an average of about 884 elements per matrix.
Ideally there would be a function that takes the matrix as input and returns a 2-column matrix with column 1 being row coordinates, column 2 being the column coordinates, and one row for each local maximum in the matrix.
Local maxima on the edges of the matrix are allowed. Areas outside of the matrix can be treated as having zero height.
Reproducible example matrix to use:
set.seed(5)
msize <- 20 # Change this to whatever you like
x <- matrix(data=abs(rnorm(msize*2)), nrow=msize, ncol=msize)