Fitting a piecewise function which depends on unknown variables

4 views (last 30 days)
Hi!
I have some problems fitting a piecewise function to my experimental data. The experimental data are the following
X=1:1:300;
Y=exp(-(2*X*0.0212)-(pi*(X.^2)*(0.0167.^2)));
Plotting X vs Y
The idea is to fit these data to a piecewise function which has the following form:
a=X./R(1);
a>=1
f=-([(a.^(-1)).*(512/(90*pi))]-[(a.^-2).*((11/24)+((1/4)*log(2*a)))]).*(X.^2).*(pi*(0.248.^2)/2)*R(2)*26.5922;
a<=1
f=-[-log(a)+(7/4)-log(2)+((a.^2)/6)-((32*(a.^3))/225*pi)].*(X.^2).*(pi*(0.248.^2)/2)*R(2)*26.5922;
y=exp(f);
The problem is that I do not know the values of R(1) and R(2) (and consequently that of a) and I have to obtain these values from the fit… I have created a function which looks like
y=function(X,R)
for i=1:1:length(X)
Xi=X(i);
X(i,:)=Xi;
ai=Xi./R(1);
if ai>=1
fi=-([(ai.^(-1)).*(512/(90*pi))]-[(ai.^-2).*((11/24)+((1/4)*log(2*ai)))]).*(Xi.^2).*(pi* (0.248.^2)/2)*R(2)*26.5922;
elseif a<=1
fi=-[-log(ai)+(7/4)-log(2)+((ai.^2)/6)-((32*(ai.^3))/225*pi)].*(Xi.^2).*(pi* (0.248.^2)/2)*R(2)*26.5922;
end
f(i,:)=fi;
end
y=exp(f);
end
Then, I call this function from the script through other function which uses the Levenberg-Marquardt algorithm to fit the data and has the following shape
[f,p,stdp,X2]=FIT_FUNCTION(X,DATA,STDEV,FUNC,P0,PFIX)
% X - Independent Variable
% DATA - Data to fit
% STDEV - Standard Deviation of each point
% FUNC - Function name to fit (string)
% P0 - Initial Guess
% PFIX - Index of parameters to fix constant
%
% F - Best fit F = FUNC(X,P)
% P - Best fit parameters
% STDP - Standard deviation of parameters
% X2 - Reduced Chi-squared
However, when I plot the fit I have something like this
And depending on the initial guesses of R(1) and R(2) it can be even worst… Also the values R(1) and R(2) determined from the fit are not reliable at all. I would be very grateful if someone could help me… Thanks in advance!

Answers (0)

Community Treasure Hunt

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

Start Hunting!