Automatically define anonymous functions.
5 次查看(过去 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.
0 个评论
采纳的回答
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 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!