r - 关于 R 中椭球体的澄清

标签 r cluster-computing ellipse

不知道是否有人可以帮我解决一些关于R包cluster中的函数ellipsoidhull的问题。我用它来查找包含一系列二维点的最小椭圆。例如

library(cluster)
d <- matrix(c(1,2,3,1,3,2),ncol=2)
e <- ellipsoidhull(d)

该函数计算椭圆 OK,返回一个包含椭圆中心和协方差矩阵的结构。

summary(e)
## 'ellipsoid' in 2 dimensions:
## center = ( 2 2 ); squared ave.radius d^2 =  2 
## and shape matrix =
##        [,1]    [,2]
##   [1,] 0.66667 0.33333
##   [2,] 0.33333 0.66667
##     hence, area  =  3.6276 

问题

a) 如何使用这些数据来检查给定点是否属于椭圆?

b) 如何使用这些数据来计算从给定点到椭圆的距离?

最佳答案

我们可以尝试以下方法:

library(cluster)
d <- matrix(c(1,2,3,1,3,2),ncol=2)
e <- ellipsoidhull(d)
eg <- eigen(e$cov)
axes <- sqrt(eg$values)
angle <- atan(eg$vectors[1,1]/eg$vectors[2,1]) # angle of major axis with x axis

# check if the point (xp, yp) belongs to the ellipse with parameters a,b,... with tolerance eps
belongs.to <- function (xp, yp, a, b, x0, y0, alpha, eps=1e-3) {
  return(abs((cos(alpha)*(xp-x0)+sin(alpha)*(yp-y0))^2/a^2+(sin(alpha)*(xp-x0)-cos(alpha)*(yp-y0))^2/b^2 - 1) <= eps)
} 

# check if the point (xp, yp) is inside the ellipse with parameters a,b,...
is.inside <- function (xp, yp, a, b, x0, y0, alpha) {
  return((cos(alpha)*(xp-x0)+sin(alpha)*(yp-y0))^2/a^2+(sin(alpha)*(xp-x0)-cos(alpha)*(yp-y0))^2/b^2 <= 1)
}

# plot ellipse
plot(e$loc, xlim=c(0,4), ylim=c(0,4), main = "ellipsoidhull", xlab='x', ylab='y')
lines(predict(e), col="blue")
points(rbind(e$loc), col = "red", cex = 3, pch = 13)

x0 <- e$loc[1] # centroid locations
y0 <- e$loc[2]  
a <- sqrt(e$d2) * axes[1]  # major axis length
b <- sqrt(e$d2) * axes[2]  # minor axis length

alpha <- angle
xp <- 3
yp <- 2.9
is.inside(xp, yp, a, b, x0, y0, alpha)
# [1] TRUE
points(xp, yp, pch=19, col='green')
xp <- 3
yp <- 3.1
is.inside(xp, yp, a, b, x0, y0, alpha)
# [1] FALSE
points(xp, yp, pch=19, col='blue')
xp <- 3
yp <- 3
belongs.to(xp, yp, a, b, x0, y0, alpha)
# [1] TRUE
points(xp, yp, pch=19, col='pink')


# distance of a point from the center of the ellipse
sqrt((xp-x0)^2+(yp-y0)^2)

enter image description here

关于r - 关于 R 中椭球体的澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42081009/

相关文章:

将特定列中的 NA 替换为同一列中相等键的值

akka - 您是否使用 Akka Cluster 在分布式系统中的每个主机上运行单独的 Actor 系统?

sql - 在数据库环境中利用集群的力量?

java - Ellipse2D 绘制精度较差

xml - "Non-zero exit status"下载 XML 和 RCurl R 包时出错

r - 在 R 数据框中按组应用计算

r - 在 R 中查找列表元素

hadoop - Hadoop集群设置…主节点也是从节点的一部分,以利用主节点内存

opencv - 如何根据当前检测到的椭圆找到更准确的椭圆

graphics - 如何画一个徒手画的椭圆或圆?