Automatically define anonymous functions.
6 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
丰源
il 19 Ott 2022
Commentato: Bjorn Gustavsson
il 19 Ott 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 Commenti
Risposta accettata
Bjorn Gustavsson
il 19 Ott 2022
Modificato: Bjorn Gustavsson
il 19 Ott 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 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Calculus in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!