Creation of a fitting function with if conditions involved
조회 수: 3 (최근 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!