简体   繁体   中英

Fitting data with heaviside step function

I have some code to fit data to heaviside function. 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.

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.

Also, I've taken xdata implicitly as the indices. But you can make that explicit also if your sample locations are irregular.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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