Why does lsqcurvefit to function with if statement take many iterations to converge and stays close to starting values?

1 次查看(过去 30 天)
Ive got this data I want to fit a function to:
The y axis mean is sometimes around 0, sometimes around 10^6 and the spike in the middle is about 4*10^2 higher or lower than the mean. The x-axis goes from 0 to 1. I want to fit a single sawtooth curve to it for which I made this function in my GUI:
function s = explicitsinglesawtooth(fitvars, t)
offset = fitvars(1);
fi = fitvars(2);
p = fitvars(3);
a = fitvars(4);
for ii=1:length(t)
if t(ii) > fi && t(ii) <= fi+p
s(ii) = offset+a*(t(ii)-fi)/p;
else
s(ii) = offset;
end
end
s = s';
(I think I can make this function nicer, however for just now Im not bothered yet by it being slow, because the current problem is bugging me more)
This I then fit with lsqcurvefit like so:
lbound = [-Inf -Inf -Inf -Inf];
ubound = [Inf Inf Inf Inf];
startvals = [mean(ydat)0.2 0.2 std(ydat)];
[fitted resnorm residual exitflag] = lsqcurvefit(@explicitsinglesawtooth, startvals, xdat, ydat, lbound, ubound, options);
This however changes almost nothing from my starting guess the first 400 function evaluations. I dont really understand why the increments per evaluation are so little. I expected my function to evaluate slowly because I did not write it down nicely, but that is something different.
So to recap: my question is why it takes so many iterations, not why one iteration takes a long time
Thanks for any help.

采纳的回答

Matt J
Matt J 2013-12-10
You aren't pre-allocating s prior to the for-loop. I'd guess that's the reason for the slow behavior.
Aside from this, though, I'm worried about differentiability issues. Your F(x,xdata) does not look like a differentiable function of x.
I'm also worried about the division by p when nothing is being done to bound p away from zero.
  2 个评论
Lennart
Lennart 2013-12-11
I agree with your worries, I should make a better function to fit to and also consider other methods than fitting to get information out of my data. However, do you think these are the reasons that it takes so many iterations?
Matt J
Matt J 2013-12-11
编辑:Matt J 2013-12-11
Possibly. What are the output values of the parameters? In fact, what are the outputs when you call lsqcurvefit with all output args
[x,resnorm,residual,exitflag,output,lambda,jacobian]=lsqcurvefit(...)

请先登录,再进行评论。

更多回答(1 个)

Matt J
Matt J 2013-12-11
This might be a better alternative,
Your saw-tooth is equivalent to a 3-knot first order spline fit.

类别

Help CenterFile Exchange 中查找有关 Get Started with Curve Fitting Toolbox 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by