How to fit a step function?

19 views (last 30 days)
Mr M.
Mr M. on 16 Sep 2015
Commented: Jörn Froböse on 10 Jun 2021
The problem is only the first parameter (p(1)) is fitted, but p1(2) = p0(2), unchanged! Why?
X = [-1.0 -0.8 -0.6 -0.4 -0.2 0.0 0.2 0.4 0.6 0.8 1.0 1.2 1.4 1.6 1.8 2.0];
Y = [0.1 -0.15 0.05 0.0 -0.05 10.2 10.5 11.5 8.2 9.2 10.0 10.5 10.2 10.9 10.5 11.5];
plot(X,Y)
step = @(x)x > 0;
fun = @(p,x) p(1)*step(x-p(2))
p0 = [9,-0.5];
p1 = lsqcurvefit(fun,p0,X,Y);
Z = fun(p1,linspace(min(X),max(X)));
hold on
plot(linspace(min(X),max(X)),Z,'r')
  1 Comment
Adam Danz
Adam Danz on 13 Apr 2021
It's not clear to me what the fit should look like or the resolution of the steps. For example,
X = [-1.0 -0.8 -0.6 -0.4 -0.2 0.0 0.2 0.4 0.6 0.8 1.0 1.2 1.4 1.6 1.8 2.0];
Y = [0.1 -0.15 0.05 0.0 -0.05 10.2 10.5 11.5 8.2 9.2 10.0 10.5 10.2 10.9 10.5 11.5];
plot(X,Y, 'b-o')
xr = [X(1),repelem(X(2:end),1,2)]; % X is row vec
yr = [repelem(Y(1:end-1),1,2),Y(end)]; % Y is row vec
hold on
plot(xr, yr, 'r-','LineWidth',2)

Sign in to comment.

Answers (1)

Figen Ece Demirer
Figen Ece Demirer on 13 Apr 2021
X = [-1.0 -0.8 -0.6 -0.4 -0.2 0.0 0.2 0.4 0.6 0.8 1.0 1.2 1.4 1.6 1.8 2.0];
Y = [0.1 -0.15 0.05 0.0 -0.05 10.2 10.5 11.5 8.2 9.2 10.0 10.5 10.2 10.9 10.5 11.5];
cut=0;
plot(X,Y,'g--o')
step = @(x)x > cut;
step2 = @(x)x < cut;
fun = @(p,x) p(1)*step(x)+p(2)*step2(x);
p0 = [9,-0.5];
p1 = lsqcurvefit(fun,p0,X,Y);
Z = fun(p1,linspace(min(X),max(X)));
hold on
plot(linspace(min(X),max(X)),Z,'r')
  1 Comment
Jörn Froböse
Jörn Froböse on 10 Jun 2021
lsqcurvefit works for continous functions only

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!