Anonymous functions in cftool GUI
3 views (last 30 days)
Show older comments
Does anyone know if it is possible to use anonymous functions in the custom equation box of the cftool GUI?
Simply typing them in results in an error in R2012a, e.g.
@(x,tau) exp(-t/tau)
Expression @(x,tau) exp(-t/tau) is not a valid MATLAB expression, has non-scalar coefficients, or cannot be evaluated:
Undefined function 'imag' for input arguments of type 'function_handle'.
My motivation is to use anonymous functions as arguments of a custom fitting function to be called by cftool, e.g.:
MyCustomFitFunction(x,hFun1,hFun2,FitParam1,FitParam2)
with hFun1 and hFun2 as function handles.
I imagine this is very possible using the non-interactive fitting tools, but was keen on using the GUI.
Thanks
0 Comments
Accepted Answer
Joe V
on 20 Aug 2014
Hi Marcelo, sorry I didn't see your comment until just now. I no longer have access to the curve fitting toolbox to test, but I think this is what you want to type into the custom equation box:
MyConvolutionFunction(x, @(x)exp(-x/a), @(x)exp(-(x-b).^2)./(2*(c.^2))))
Here's how that works: Whenever cftool wants to evaluate your analytic function, it evaluates the above expression. In doing so, it creates two anonymous function handles, and then passes them (along with x) into MyConvolutionFunction. The anonymous function handles are created with only x as an argument, so the values of a, b, and c are drawn from the workspace at the time the function handles are created (i.e. when cftool is evaluating the expression). I believe this should work. One note: I am guessing that cftool uses inline to parse the expression in the custom equation box. In my own testing, I noticed that inline isn't smart enough to identify the parameters of anonymous functions. This means it's important that you make the anonymous function argument @(x). If you use some other variable like @(t), then inline will erroneously think that t is another parameter in your expression that cftool needs to provide, and that will cause problems for cftool.
One more comment: Function handles in MATLAB incur a slight performance penalty over typing in expressions directly, so if you find cftool is unacceptably slow you can try the "hard-coded" approach.
Hope this helps!
0 Comments
More Answers (2)
Joe V
on 28 Sep 2013
You don't need to use an anonymous function. Just type in your function, making sure to use x as the independent variable:
exp(-x/tau)
The Curve Fitting Tool will recognize x as the independent variable and tau as a parameter of the fit. (If the curve you want to fit to is literally exp(-x/tau), you might not need a custom equation -- the Exponential fit type will fit to the curve a*exp(b*x).)
See Also
Categories
Find more on Get Started with Curve Fitting Toolbox in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!