Creation of a fitting function with if conditions involved
3 views (last 30 days)
Show older comments
Hello everyone
I am trying to create a fitting function in a separate script from where I'm handling the data (let's call the involved arrays x and y), but this is my first try with this kind of functionality in MatLab. I want this function to use a different functional form depending on the first and last values of the y array, so I have something like
function [fitresult,gof]=fitting(x,y)
% Now, I create my possible fitting functions
if round(y(1),1)==0.7 && round(y(end),1)==0.7
fitting_function=@(x,x0,Delta)((1/sqrt(2))*(sin(atan(exp((x-x0)/Delta)))+cos(atan(exp((x-x0)/Delta)))));
elseif round(y(1),1)==-0.7 && round(y(end),1)==-0.7
fitting_function=@(x,x0,Delta)(-(1/sqrt(2))*(sin(atan(exp((x-x0)/Delta)))+cos(atan(exp((x-x0)/Delta)))));
elseif round(y(1),1)==-0.7 && round(y(end),1)==0.7
fitting_function=@(x,x0,Delta)((1/sqrt(2))*(sin(atan(exp((x-x0)/Delta)))-cos(atan(exp((x-x0)/Delta)))));
elseif round(y(1),1)==0.7 && round(y(end),1)==-0.7
fitting_function=@(x,x0,Delta)(-(1/sqrt(2))*(sin(atan(exp((x-x0)/Delta)))-cos(atan(exp((x-x0)/Delta)))));
end
% Now, the fitting itself
ft=fittype(fitting_function,'independent','x','dependent','y');
opts=fitoptions('Method','NonlinearLeastSquares');
[fitresult, gof]=fit(xData,yData,ft,opts);
This is just an approximation of how it could look like. I want to do it more or less this way without specifying the initial values of x0 and Delta in the function environment, but doing it in the script with the data (unless that I can do it also in the function environment, looking for x0 which is the point of the x array closer to 0 and for Delta which is the full width at half maximum of the y array).
Any suggestion?
0 Comments
Answers (1)
John D'Errico
on 22 Feb 2022
Edited: John D'Errico
on 22 Feb 2022
NEVER do things like this using floating point numbers.
round(y(1),1)==0.7
While that may work, will it always? Will it necessarily succeed? Not always. For example, surely this is a mathematical truism, is it not?
find(round((1:50)/10,1) ~= (0.1:.1:5))
So there were actually 16 out of 50 cases where the mathematically obvious fails to be true.
Learn about tolerances when you are working with floating point numbers, even if you do use round!
0 Comments
See Also
Categories
Find more on Curve Fitting Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!