# 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!

``````library(tidyverse)
library(colorspace)
library(slider)

(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,
~euclidean_distance(c(.\$x,.\$y),mycenter))

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

ggplot(data=myspace,
mapping = aes(x=x,
y=y,
fill=dist_to_mycenter)) + geom_tile() +
scale_fill_continuous_diverging(mid=0)``````
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.