Automatically define anonymous functions.

5 views (last 30 days)
Here are my code:
clear
C=[-1,1,1+1/4*i,-1+1/4*i];
syms x;
f=@(x) x.^2 + 1/4;
df=diff(f,x);
fun = df/f;
%fun=@(x) (df/f);
fun =@(x) ((2.*x)./(x.^2 + 1/4));
a=abs(integral( fun,1,1,'Waypoints',C))
I need to compute complex line integrals by the function integral(fun,xmin,xmax,Name,Value). And this function requires that the fun parameter must have an function handler. But my input parameter fun is defined by df/f, which will be changed through variable f.
If I use the annotated code fun=@(x) (df/f), the MATLAB will report an error that "The input function must return a 'double' or 'single' value. Find 'sym'."
Therefore I have to define the anonymous function manually, which is very annoying. Is there any method for automatically defining the anonymous functions? Please help me.

Accepted Answer

Bjorn Gustavsson
Bjorn Gustavsson on 19 Oct 2022
Edited: Bjorn Gustavsson on 19 Oct 2022
You can solve this problem using matlabFunction to generate a function-handle:
C=[-1,1,1+1/4*i,-1+1/4*i];
syms x;
f=@(x) x.^2 + 1/4;
df=diff(f,x);
fun = df/f;
fun = matlabFunction(fun);
% Returns a function-handle:
% fun =
%
% function_handle with value:
%
% @(x)(x.*2.0)./(x.^2+1.0./4.0)
% suitable for integration:
a=abs(integral( fun,1,1,'Waypoints',C))
If you have more parameters in your symbolic expression, then those will be input-arguments to the function-handle, which makes the integration-step a fair bit more klunky. Then you'll have to figure out which order the arguments come in and how to convert that function-handle to a function-handle with the correct fixed and variable input-arguments. But this should solve this problem.
HTH
  2 Comments
丰源
丰源 on 19 Oct 2022
That is exactly what I want !!!
Thank you very much :)

Sign in to comment.

More Answers (0)

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!