有时候的实验室数据图像得到的如下图所示:
当然之前中过冷水多次有跟大家提多项式拟合、傅里叶级数拟合、高斯级数拟合,实际更加常见的操作是用matlab中图像拟合工具箱cftool灵活进行函数拟合。
这个过程大多数读者应该都有了解,问题在于:“how to get fit data”?首先我们需要先把函数工具拟合方法生成代形式:
function [fitresult, gof] = createFit(x1, y1)
%CREATEFIT(X1,Y1)
% Create a fit.
%
% Data for 'untitled fit 1' fit:
% X Input : x1
% Y Output: y1
% Output:
% fitresult : a fit object representing the fit.
% gof : structure with goodness-of fit info.
%
% 另请参阅 FIT, CFIT, SFIT.
% 由 MATLAB 于 06-Sep-2020 19:30:43 自动生成
%% Fit: 'untitled fit 1'.
[xData, yData] = prepareCurveData( x1, y1 );
% Set up fittype and options.
ft = fittype( 'smoothingspline' );
% Fit model to data.
[fitresult, gof] = fit( xData, yData, ft );
% Plot fit with data.
figure( 'Name', 'untitled fit 1' );
h = plot( fitresult, xData, yData );
legend( h, 'y1 vs. x1', 'untitled fit 1', 'Location', 'NorthEast' );
% Label axes
xlabel x1
ylabel y1
grid on
生成代码形式后,对代码进行简化,可以得到如下代码:
clear;
x1=[2,2.89795918367347,2.94897959183673,2.97959183673469,2.98979591836735,3.01020408163265,3.03061224489796,3.06122448979592,3.10204081632653,3.14285714285714,3.24489795918367,3.29591836734694,3.34693877551020,3.39795918367347,3.43877551020408,3.48979591836735,3.56122448979592,3.67346938775510,3.82653061224490,4.06122448979592,4.32653061224490,4.65306122448980,5,5.26530612244898,5.56122448979592,5.88775510204082,6.11224489795918,6.33673469387755,6.62244897959184,6.98979591836735,7.47959183673469,7.98979591836735];
y1=[0,0.524822695035461,0.978723404255319,1.31205673758865,1.57446808510638,1.82978723404255,2.04964539007092,2.31914893617021,2.63120567375887,2.85815602836879,2.82269503546099,2.59574468085106,2.34042553191489,2.08510638297872,1.87234042553192,1.64539007092199,1.38297872340426,1.11347517730496,0.936170212765958,0.858156028368794,0.900709219858156,0.964539007092199,0.929078014184397,0.829787234042553,0.787234042553191,0.872340425531915,1.02836879432624,1.17730496453901,1.20567375886525,1.07801418439716,0.964539007092199,0.921985815602837];
f=fit(x1',y1','smoothingspline');
x2=linspace(2,8,100)';
y2=f(x2);
figure1 = figure;
subplot1 = subplot(2,1,1,'Parent',figure1);
hold(subplot1,'on');
plot(x1,y1,'Parent',subplot1,'LineWidth',2);
xlabel('$x$','Interpreter','latex');
ylabel('$y$','Interpreter','latex');
title('原始数据','Interpreter','latex');
set(subplot1,'FontSize',12,'LineWidth',2);
subplot2 = subplot(2,1,2,'Parent',figure1);
hold(subplot2,'on');
plot(x2,y2,'Parent',subplot2,'LineWidth',2);
xlabel('$x$','Interpreter','latex');
ylabel('$y$','Interpreter','latex');
title('插值拟合数据','Interpreter','latex');
set(subplot2,'FontSize',12,'LineWidth',2);
这样(x2,y2)就是我们想要的所有插值拟合数据,还有一种查绘图数据的方法。
h=plot(x1,y1)
x=get(h,'xdata');
y=get(h,'ydata');
该段代码主要是有时候再特殊情况下我们先是得到具体的函数图像而不是绘图数据,所以就需要使用该段代码就有用了。冷水现在再讲讲如何提取特殊点方法。可以用
[X,Y]=ginput(2)
X =
3.2373
3.4171
Y =
2.7808
2.2558
、
本期过冷水和大家分享的知识容量短小精炼,对于初学者都能够使用上而不是以往的那些晦涩深奥的知识,希望能够对读者有帮助。
如需转载,请在公众号中回复“转载”获取授权,未经授权擅自搬运抄袭的,必将追究其责任!