Question

In my experiment, I need to approximate or fitting a measurement y = f_m(x) with n linear segments. Value of n can be selected to be 1, 2, 3, 4, 5... and probably less than 10. For clarity, it's good if the errors from different cases can be compared to find the one with smallest error.

I've found one example using MATLAB (link):

% Random data...
xdata = linspace(-2,3,101);
ydata = log(abs(10./(10+1i*10.^xdata))) + 0.5*randn(size(xdata));
plot(xdata,ydata)
F = @(B,xdata) min(B(1),B(2)+B(3)*xdata);   %Form of the equation
IC = [max(ydata) max(ydata) 0]; %Initial guess
B = lsqcurvefit( F,IC,xdata,ydata,[min(ydata) -inf -inf],[max(xdata) inf 0]);
hold all;
plot(xdata,F(B,xdata));
a = (B(1) - B(2)) / B(3)
cte = B(1)
c = B(2)
d = B(3)

This is similar to what I'm looking for in the case of 2 segments. I tried to modify this function to suit my need with changing the function handle:

F = @(B,xdata) min(B(1),B(2)+B(3)*xdata);   %Form of the equation

to

F = @(B,xdata) min(B(1)+B(2)*xdata,B(3)+B(4)*xdata);

but it seems my modification results in 2 segments on the same line.

I don't know much about MATLAB function handle. Especially here, there is "min" function in it. Moreover, how should I do to extend this example to several linear segments?

Thank you in advance!!

Edit01:

Thanks!! your answer has made my code run as desired. But, may I ask a little on the question here. As previously mentioned, I originally want to extend the approximation to several linear segments. So, I go like:

F = @(B,xdata) min(B(1)+B(2)*xdata, B(3)+B(4)*xdata, B(5)+B(6)*xdata);   %Form of the equation
IC = [max(ydata) max(ydata) max(ydata) max(ydata) max(ydata) 0]; %Initial guess
B = lsqcurvefit( F,IC,xdata,ydata,[min(ydata) -inf -inf -inf -inf -inf],[max(xdata) inf inf inf inf 0]);

but MATLAB response with I.C. error:

Failure in initial user-supplied objective function evaluation

Can you help me shortly with the I.C here? and what's with the "min" function in function handle?

Was it helpful?

Solution

I get the following error when running your code :

??? Error using ==> lsqncommon at 101
LSQCURVEFIT cannot continue because user supplied objective function failed with the following error:
Attempted to access B(4); index out of bounds because numel(B)=3.

Hence, this means that there is nothing in B(4). I would try to modify IC, lb and ub to have 4 elements.

So try to put these two lines in your code :

IC = [max(ydata) max(ydata) max(ydata) 0]; %Initial guess
B = lsqcurvefit( F,IC,xdata,ydata,[min(ydata) -inf -inf -inf],[max(xdata) inf inf 0]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top