Automatically define anonymous functions.
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
丰源
am 19 Okt. 2022
Kommentiert: Bjorn Gustavsson
am 19 Okt. 2022
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 Kommentare
Akzeptierte Antwort
Bjorn Gustavsson
am 19 Okt. 2022
Bearbeitet: Bjorn Gustavsson
am 19 Okt. 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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Calculus finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!