Matlab根据数据拟合圆及拟合效果对比
程序员文章站
2022-03-31 20:53:06
...
1. 前言
本实例为自己摘录之后根据个人需求更改后上传。
实现的功能为:将txt中的数据进行导入matlab,并拟合圆,求圆心坐标及画圆对比。
txt文件中一共三列,每列之间以逗号隔开。
2. 代码
// An highlighted block
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear all;
clc;
filename = '.\1.txt'; % 文件名
[date1,date2,~] = textread(filename,'%n%n%n','delimiter', ',');%读取文件中数据到date i
y0 = date1;
x0 = date2;
circ(x0,y0);
% 读取文件中数据并导入函数circ中
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [R,A,B]=circ(x,y) %拟合函数
x1 = 0;
x2 = 0;
x3 = 0;
y1 = 0;
y2 = 0;
y3 = 0;
x1y1 = 0;
x1y2 = 0;
x2y1 = 0;
N=length(x);
for i = 1 : N
x1 = x1 + x(i);
x2 = x2 + x(i)*x(i);
x3 = x3 + x(i)*x(i)*x(i);
y1 = y1 + y(i);
y2 = y2 + y(i)*y(i);
y3 = y3 + y(i)*y(i)*y(i);
x1y1 = x1y1 + x(i)*y(i);
x1y2 = x1y2 + x(i)*y(i)*y(i);
x2y1 = x2y1 + x(i)*x(i)*y(i);
end
C = N * x2 - x1 * x1;
D = N * x1y1 - x1 * y1;
E = N * x3 + N * x1y2 - (x2 + y2) * x1;
G = N * y2 - y1 * y1;
H = N * x2y1 + N * y3 - (x2 + y2) * y1;
a = (H * D - E * G)/(C * G - D * D);
b = (H * C - E * D)/(D * D - G * C);
c = -(a * x1 + b * y1 + x2 + y2)/N;
A = a/(-2); % x 坐标
B = b/(-2); % y 坐标
R = sqrt(a * a + b * b - 4 * c)/2; %分别为所拟合的圆心的坐标和半径
set(gca,'xlim',[0,600]);
set(gca,'ylim',[500,1000]); %我为了对比每个拟合的圆的大小和坐标,故设定了一个固定的坐标系
hold on;
plot(A,B,'r.','MarkerSize',20); %显示所拟合的圆心
hold on;
Q = [x,y];%
n = Q(:,1);
m = Q(:,2);
plot(n,m); %做出原始点的曲线,与所拟合的曲线进行对比,观察原始曲线和所拟合曲线的区别
hold on;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
theta=0:2*pi/3600:2*pi;
Circle1=A+R*cos(theta);
Circle2=B+R*sin(theta);
plot(Circle1,Circle2,'m','Linewidth',1); %画出所拟合的圆
saveas(gcf,'1.jpg'); % 自动保存所做的图片到程序路径
axis equal
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3. 原理
博主菜鸡,没来得及搞原理,只知道是最小二乘法。
下面附上原始博文链接,留着自已以后再看
原代码来源于大神博客https://blog.csdn.net/Msjiangmei/article/details/82970788
上一篇: 圆的散点拟合, 已知圆的采样点, 求圆的圆心和半径.
下一篇: 封装多帧dicm图像
推荐阅读