You can get an approximation using Monte Carlo method:
a = matrix(c(0 ,0 ,2 ,0 ,2 ,2 ,0 , 2, 0, 0), byrow = T, ncol = 2)
b = matrix(c(.5, 0 ,1 , 1, 1.5, 0, .5, 0), ncol = 2, byrow = T)
library(sp)
interseccao <- function(a,b, n = 100000){
xmin <- min(a[,1], b[,1])
xmax <- max(a[,1], b[,1])
ymin <- min(a[,2], b[,2])
ymax <- max(a[,2], b[,2])
x_aleatorio <- runif(n, min = xmin, max = xmax)
y_aleatorio <- runif(n, min = ymin, max = ymax)
pontos_em_a <- point.in.polygon(x_aleatorio, y_aleatorio, pol.x = a[,1], pol.y = a[,2])
pontos_em_b <- point.in.polygon(x_aleatorio, y_aleatorio, pol.x = b[,1], pol.y = b[,2])
proporcao_intersec <- mean(pontos_em_a == 1 & pontos_em_b == 1)
area_intersec <- (xmax-xmin)*(ymax - ymin)*proporcao_intersec
return(area_intersec)
}
interseccao(a,b)
[1] 0.50368
In the Monte Carlo Method, random dots are generated in an area from which you already know the area. Then we determine the proportion of points that occur in the area you want to calculate, in this case, at the intersection of polygons. This proportion multiplied by the area in which the points were generated, returns the desired area.
Of course there must be an algorithm that calculates the exact area, but if an approximation is enough for you, it’s here.
The problem @Daniel is that I need to calculate the area of about 5000 polygons and use Monte Carlo will get very heavy, but solution is quite interesting.
– Wagner Jorge
Wagner, you can give an idea of the purpose of this, I think it will help us understand.
– Leo
@Wagnerjorge agree that it can get heavy, to calculate this amount would take about 3min (the execution time of the function is around 35 ms). Anyway, this is just an idea, suddenly you can give up precision by taking a smaller sample for the Monte Carlo and thus accelerate the calculation. I’ve heard it’s better to waste processing time than programming :P
– Daniel Falbel