visualize the (Euclidean) distances from a point in my matrix to every other point?

Hi everyone,

This one has turned out to be a real brain teaser for me. I have 7 x 7 matrix, but the values are meaningless, so I'll just set them to zero:

mymat <- matrix(ncol=7,nrow=7, 0)

I want to measure the Euclidean distance from the center of this matrix to every other square in this matrix, and visualize the results in kind of a heatmap plot. Defining the center and distance function is easy:

mycenter <- mymat[4,4]

euclidean_distance <- function(p,q){
  sqrt(sum((p - q)^2))

I'm not sure where to go from here - but I'm thinking it would require a for loop over each index of the matrix applying the distance function, then to melt and plot with ggplot (since trying to plot the matrix itself would mess up the order of the rows/cols ?)

Any ideas? thanks!


(myspace <- expand.grid(x=1:7,y=1:7))

(mycenter <-c(4,4))

euclidean_distance <- function(p,q){
  sqrt(sum((p - q)^2))

myspace$dist_to_mycenter <- slide_dbl(myspace,

#if you want to see it in matrix shape (but I dont use this transform anywhere)
            id_cols ="x",
            names_from = "y",
            values_from = "dist_to_mycenter")

        mapping = aes(x=x,
                      fill=dist_to_mycenter)) + geom_tile() +
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.