如何使用R查找最合适的圆/椭圆? [英] How to find a best fit circle/ellipse using R?

查看:120
本文介绍了如何使用R查找最合适的圆/椭圆?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读一些使圆适合数据的方法(例如

I've been reading about a few methods to fit a circle to data (like this). I would like to see how the methods work on real data and thought of using R for this. I tried searching rseek for packages that can help with this but came up with nothing useful.

那么,是否有一些软件包可以帮助轻松地计算给定数据集的最佳拟合圆(类似于lm()如何将线性模型拟合到数据集)?否则,如何在R中执行这样的任务?

So, are there packages that help to easily compute the best fit circle for a given data set (similar to how lm() will fit a linear model to a data set)? Otherwise, how might one perform such a task in R?

推荐答案

以下是该函数的一个非常幼稚的实现,该函数最小化了该论文中的SS(a,b,r):

Here's a fairly naive implementation of a function that minimises SS(a,b,r) from that paper:

fitSS <- function(xy,
                  a0=mean(xy[,1]),
                  b0=mean(xy[,2]),
                  r0 = mean(sqrt((xy[,1]-a0)^2 + (xy[,2]-b0)^2)),
                  ...){
    SS <- function(abr){
        sum((abr[3] - sqrt((xy[,1]-abr[1])^2 + (xy[,2]-abr[2])^2))^2)
    }
    optim(c(a0,b0,r0), SS, ...)
}

我编写了一些支持功能,可以在圆上生成随机数据并绘制圆.因此:

I've written a couple of supporting functions to generate random data on circles and to plot circles. Hence:

> xy = sim_circles(10)
> f = fitSS(xy)

fit$par值是xcenter,ycenter,radius的向量.

The fit$par value is a vector of xcenter, ycenter, radius.

> plot(xy,asp=1,xlim=c(-2,2),ylim=c(-2,2))
> lines(circlexy(f$par))

请注意,它不使用渐变,也不检查错误代码的收敛性.您可以为其提供初始值,也可以进行猜测.

Note it doesn't use the gradients nor does it check the error code for convergence. You can supply it with initial values or it can have a guess.

用于绘制和生成圆的代码如下:

Code for plotting and generating circles follows:

circlexy <- function(xyr, n=180){
    theta = seq(0,2*pi,len=n)
    cbind(xyr[1] + xyr[3]*cos(theta),
          xyr[2] + xyr[3]*sin(theta)
          )
}
sim_circles <- function(n,x=0,y=0,r=1,sd=0.05){
    theta = runif(n, 0, 2*pi)
    r = r + rnorm(n, mean=0, sd=sd)
    cbind(x + r*cos(theta),
          y + r*sin(theta)
      )
}

这篇关于如何使用R查找最合适的圆/椭圆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆