如何在Matlab中通过一系列分段线拟合曲线?

Cas*_*sie 5 matlab plot curve-fitting numerical-methods

在此输入图像描述

我有一个如上所述的简单loglog曲线.Matlab中是否有一些函数可以通过分段线拟合这条曲线并显示这些线段的起点和终点?我在matlab中检查了曲线拟合工具箱.它们似乎通过一条线或一些函数进行曲线拟合.我不想只用一条曲线拟合.

如果没有直接的功能,任何实现相同目标的替代方案都可以.我的目标是通过分段线拟合曲线并获得这些段的端点的位置.

And*_*ein 7

首先,您的问题不称为曲线拟合.曲线拟合就是在您拥有数据时,从某种意义上说,您可以找到描述它的最佳函数.另一方面,您希望创建函数的分段线性逼近.

我建议采取以下策略:

  1. 手动拆分为部分.截面尺寸应取决于导数,大导数 - >小截面
  2. 在节之间的节点处对函数进行采样
  3. 找到通过上述点的线性插值.

以下是执行此操作的代码示例.您可以看到红线(插值)非常接近原始函数,尽管部分数量很少.这是由于自适应部分大小而发生的.

在此输入图像描述

function fitLogLog()
   x = 2:1000;
   y = log(log(x));

   %# Find section sizes, by using an inverse of the approximation of the derivative
   numOfSections = 20;
   indexes = round(linspace(1,numel(y),numOfSections));
   derivativeApprox = diff(y(indexes));
   inverseDerivative = 1./derivativeApprox;
   weightOfSection =  inverseDerivative/sum(inverseDerivative);   
   totalRange = max(x(:))-min(x(:));   
   sectionSize = weightOfSection.* totalRange;

   %# The relevant nodes
   xNodes = x(1) + [ 0 cumsum(sectionSize)];
   yNodes = log(log(xNodes));

   figure;plot(x,y);   
   hold on;
   plot (xNodes,yNodes,'r');
   scatter (xNodes,yNodes,'r');
   legend('log(log(x))','adaptive linear interpolation');
end
Run Code Online (Sandbox Code Playgroud)


cjh*_*cjh 5

Andrey的自适应解决方案提供更准确的整体适应性.但是,如果您想要的是固定长度的片段,那么这里应该可以使用一种方法,该方法也返回所有拟合值的完整集合.如果需要速度,可以进行矢量化.

Nsamp = 1000;     %number of data samples on x-axis
x = [1:Nsamp];    %this is your x-axis
Nlines = 5;       %number of lines to fit

fx = exp(-10*x/Nsamp);  %generate something like your current data, f(x)
gx = NaN(size(fx));     %this will hold your fitted lines, g(x)

joins = round(linspace(1, Nsamp, Nlines+1));  %define equally spaced breaks along the x-axis

dx = diff(x(joins));   %x-change
df = diff(fx(joins));  %f(x)-change

m = df./dx;   %gradient for each section

for i = 1:Nlines
   x1 = joins(i);   %start point
   x2 = joins(i+1); %end point
   gx(x1:x2) = fx(x1) + m(i)*(0:dx(i));   %compute line segment
end

subplot(2,1,1)
h(1,:) = plot(x, fx, 'b', x, gx, 'k', joins, gx(joins), 'ro');
title('Normal Plot')

subplot(2,1,2)
h(2,:) = loglog(x, fx, 'b', x, gx, 'k', joins, gx(joins), 'ro');
title('Log Log Plot')

for ip = 1:2
    subplot(2,1,ip)
    set(h(ip,:), 'LineWidth', 2)
    legend('Data', 'Piecewise Linear', 'Location', 'NorthEastOutside')
    legend boxoff
end
Run Code Online (Sandbox Code Playgroud)

MATLAB绘制输出