使用重载步进功能拟合数据

问题描述 投票:2回答:1

我有一些代码可以将数据与weightiside函数相匹配。但是,拟合程序无法正常工作。它的变化很大程度上取决于初始条件,并且无法找到最小值。有人可以帮忙吗?我已粘贴下面的代码,示例脚本并使用y-data附加文件。

ydata=[10 8 12 8 14 9 11 10 200 210 190 190 201 205 203 206 185 30 28 32 35 28 33 29];  
n=length(ydata);
xdata=[1:n];

%function
predicted = @(a,xdata) a(1)*heaviside(xdata-a(2))-a(3)*heaviside(xdata-a(4));

%initial conditions
a0 = [10;8;200;18];

% Fit model to data.
[ahat,resnorm,residual,exitflag,output,lambda,jacobian]=lsqcurvefit(predicted,a0,xdata,ydata);

% Plot fit with data.
plot(xdata,ydata);   

%plot fits
opts = fitoptions( 'Method', 'NonlinearLeastSquares');

%plot fit function
fitfinal = ahat(1)*heaviside(xdata-ahat(2))-ahat(3)*heaviside(xdata-ahat(4));

hold on 
plot(xdata,fitfinal)
hold off

最后,我想提取水平部分的长度。

matlab function curve-fitting
1个回答
2
投票

这是一个很容易适应的功能。只需找两个有大跳的地方:

plot(ydata)
hold on

dy = abs(diff(ydata));
[~,index] = sort(dy,'descend');

% First segment = 1:index(1)
m = mean(ydata(1:index(1)));
plot([1,index(1)],[m,m])

% Second segment = index(1)+1:index(2)
m = mean(ydata(index(1)+1:index(2)));
plot([index(1)+1,index(2)],[m,m])

% Third segment = index(2)+1:length(ydata)
m = mean(ydata(index(2)+1:length(ydata)));
plot([index(2)+1,length(ydata)],[m,m])

作为“拟合函数”,我使用函数的平均值绘制了这些段,但所有信息都是使用两个Heaviside函数组成函数。

另外,我把xdata隐含地作为指数。但是,如果您的样本位置不规则,您也可以明确说明。

© www.soinside.com 2019 - 2024. All rights reserved.