Automatically define anonymous functions.

4 次查看(过去 30 天)
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.

采纳的回答

Bjorn Gustavsson
Bjorn Gustavsson 2022-10-19
编辑:Bjorn Gustavsson 2022-10-19
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Calculus 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by