Fitting to a homemade function

1 view (last 30 days)
Andreas Pedersen
Andreas Pedersen on 25 Jan 2018
Answered: Andreas Pedersen on 26 Jan 2018
I have created my homemade function based on three parameters where two of them are fixed and the last parameter, D, needs to be tuned in.
ydata=MyFun(a,H,D,xdata)
I would like to use the lsqcurvefit function but how do I tell it that it need to fit to D only, and yet still have a and H as input parameters? Id like to create something as below...
x = lsqcurvefit(@MyFun,a,H,*D*,xdata,ydata)
best Andreas

Answers (2)

Adam
Adam on 25 Jan 2018
x = lsqcurvefit(@(D, xData) MyFun( a, H, D, xdata ),ydata )
should work, I think...
  4 Comments
Andreas Pedersen
Andreas Pedersen on 26 Jan 2018
Walter you are correct, a and H changed, it doesnt matter though, they are both single value length parameters of a "squarish" cylinder.
does it matter that some of the xData's are with a capital D and some are not?
It seems like the fit only goes through one iteration and sets x=initial guess (D0)
Walter Roberson
Walter Roberson on 26 Jan 2018
In the expression
@(D, xData) uptake( Var.H, Var.a, D, xData )
xData is a dummy parameter name for a positional parameter that will correspond to some or all of the x data that is passed as the third parameter to lsqcurvefit . I used a different name to emphasize that they are not actually the same variable.
Because parameter passing is positional, without changing the meaning of the expression at all, I could have used something like
@(D, x_data_parameter) uptake( Var.H, Var.a, D, x_data_parameter)
"It seems like the fit only goes through one iteration and sets x=initial guess (D0)"
That is possible, if D0 just happens to generate a residue that is within the tolerance. That can happen due to good initial guess, or due to chance, or due to error in the residue calculation (such as if uptake returned 0), or if the values of the function happen to be naturally small so that the residues come out with small absolute value.

Sign in to comment.


Andreas Pedersen
Andreas Pedersen on 26 Jan 2018
I have solved it partly with he help from you, thank you for giving the correct way of creating the matlab function. I ended up sacrificing a and H as input parameters and from there use the simpler form:
D0=1e-15;
options = optimset('FunValCheck', 'on',...
'MaxFunEvals',1*10^10,...
'TolX',1e-30,...
'TolFun',1e-30,...
'MaxIter', 1*10^10,...
'Display','off');
D = lsqcurvefit(@uptake,D0,xdata,ydata,1e-12,1e-10,options);
To overcome the single iteration problem I figured that it was the 'TolFun' in "options" that needed to be reduced from the standard 1e-6 to something way lower. When i check my fit on function data i get complete coherence so it all checks out.
Thank you for your help. Best, Andreas

Community Treasure Hunt

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

Start Hunting!