Creation of a fitting function with if conditions involved
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
John D'Errico
2022-2-22
编辑:John D'Errico
2022-2-22
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Curve Fitting Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!