简体   繁体   English

使用 heaviside 阶跃函数拟合数据

[英]Fitting data with heaviside step function

I have some code to fit data to heaviside function.我有一些代码可以将数据拟合到 heaviside 函数。 However, the fitting routine is not working properly.但是,拟合例程无法正常工作。 It varies so much dependent on the initial conditions and cant find the minimum.它因初始条件而异,无法找到最小值。 Can someone help?有人可以帮忙吗? I have pasted the code below, the sample script and attached the file with the y-data.我粘贴了下面的代码、示例脚本并附加了带有 y 数据的文件。

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

In the end I would like to extract the lengths of the horizontal sections.最后我想提取水平部分的长度。

This is a trivial function to fit.这是一个微不足道的函数。 Simply look for the two places where there is a big jump:只需寻找有大跳跃的两个地方:

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])

As a "fitted function" I've plotted the segments using the mean of the function across those samples, but all the information is there to compose a function using two Heaviside functions.作为“拟合函数”,我使用这些样本中函数的平均值绘制了段,但所有信息都可以使用两个 Heaviside 函数组成一个函数。

Also, I've taken xdata implicitly as the indices.另外,我已经隐式地将xdata作为索引。 But you can make that explicit also if your sample locations are irregular.但是,如果您的样本位置不规则,您也可以明确说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM