###### 嘛呐嘿
2019-04-17 17:02 阅读 582

# 如何用matlab分组运算

ps：本人使用的是Matlab r2018a，运行环境的macos

`````` x = [4.1441    0
4.4684  0
5.7308  0.002
9.4417  0.0042
11.6335 0.0059
13.4882 0.0073
14.247  0.0078
14.6688 0.008
13.7427 0.0068
11.8059 0.0044
8.6033  0.0015
5.2315  -0.0013
1.6184  -0.0036
-0.8267 -0.0055
-3.5249 -0.0076
-5.0424 -0.0089
-5.97   -0.0096
-5.9694 -0.0099
-5.5492 -0.0089
-3.0212 -0.0062
-0.4088 -0.0035];
%  p0=[1 1 1 1 1 1];
p0=[0.005 0.005 0.005 0.005 0.005 0.005];
warning off
F=@(p,x)p(1)*x(:,1).^2+p(2)*x(:,1).*x(:,2)+p(3)*x(:,2).^2+p(4)*x(:,1)+p(5)*x(:,2)+p(6);
% 拟合系数，最小二乘方法
p=nlinfit(x,zeros(size(x,1),1),F,p0);
p(1)
p(2)
p(3)
p(4)
p(5)
p(6)

A=p(1)/p(6);
B=p(2)/p(6);
C=p(3)/p(6);
D=p(4)/p(6);
E=p(5)/p(6);

%%椭圆中心
X_center = (B*E-2*C*D)/(4*A*C - B^2);
Y_center = (B*D-2*A*E)/(4*A*C - B^2);
fprintf(' X_center=%g, Y_center=%g\n',X_center,Y_center);
%%长短轴
a= 2*sqrt((2*A*(X_center^2)+2*C*(Y_center^2)+2*B*X_center*Y_center-2)/(A+C+sqrt(((A-C)^2+B^2))));
b= 2*sqrt((2*A*(X_center^2)+2*C*(Y_center^2)+2*B*X_center*Y_center-2)/(A+C-sqrt(((A-C)^2+B^2))));

%%长轴倾角
q=0.5 * atan(B/(A-C));
fprintf(' q=%g\n',q);

fprintf(' a=%g, b=%g\n',a,b);
plot(x(:,1),x(:,2),'ro');

hold on;
xmin=min(x(:,1));
xmax=max(x(:,1));
ymin=min(x(:,2));
ymax=max(x(:,2));
xmid=(xmax+xmin)/2;
ymid=(ymax+ymin)/2;
stri=(xmax-xmid)*(ymax-ymid)/2;
S=a*b*pi;
z=S/4/pi/stri;
% 将数据组集到data
data = [xmin',ymin',xmax',ymax',xmid',ymid',a', b', A', B',C',D',E',stri',S',z'];
% 将data切割成m*n的cell矩阵
[m, n] = size(data);
data_cell = mat2cell(data, ones(m,1), ones(n,1));
% 添加变量名称
title = {'xmin','ymin','xmax','ymax','xmid','ymid','a', 'b', 'A', 'B','C','D','E','stri','S','z'};
% 将变量名称和数值组集到result
result = [title; data_cell];
% 将result写入到wind.xls文件中
s = xlswrite('wind.xls', result);

% 作图
%ezplot(@(x,y)F(p,[x,y]),[xmin,xmax,ymin,ymax]);
%title('曲线拟合');
%legend('样本点','拟合曲线')

``````
• 点赞
• 写回答
• 关注问题
• 收藏
• 复制链接分享