How to fit a step function?

16 次查看(过去 30 天)
Mr M.
Mr M. 2015-9-16
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 个评论
Adam Danz
Adam Danz 2021-4-13
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)

请先登录,再进行评论。

回答(1 个)

Figen Ece Demirer
Figen Ece Demirer 2021-4-13
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')

类别

Help CenterFile Exchange 中查找有关 Least Squares 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by