How to use str2func with a function handle in the string

9 visualizaciones (últimos 30 días)
dario
dario el 29 de Mayo de 2020
Comentada: dario el 29 de Mayo de 2020
Hi,
I want to insert a function handle in the input string of str2func but I get an error.
string1 = '@(x)sin(x)';
A = str2func(string1);
string2 = '@(x,y)(A(x) + sin(y))'
B = str2func(string2);
B(pi/2,pi/2)
It says: Undefined function or variable 'A'.
How can I fix it?
Thanks

Respuesta aceptada

Tommy
Tommy el 29 de Mayo de 2020
"Workspace variables are not available to the str2func function."
See this answer. You could do something like this:
string1 = '@(x)sin(x)';
A = str2func(string1);
string2 = ['@(y)(' num2str(feval(A,pi/2)) ' + sin(y))'];
B = str2func(string2);
B(pi/2)
  6 comentarios
Tommy
Tommy el 29 de Mayo de 2020
Gotcha. There's always eval...
string1 = '@(x)sin(x)';
A = str2func(string1);
string2 = '@(x,y)(A(x) + sin(y))';
B = eval(string2);
B(pi/2,pi/2)
I guess I ignore eval by default, but it definitely works here. I would still recommend either of the previous answers.
Or here's a somewhat interesting possibility:
string1 = '@(x)sin(x)';
A = str2func(string1);
string2 = @(x) (['@(y)(' num2str(feval(A,x)) ' + sin(y))']);
B = @(x,y) feval(str2func(string2(x)), y);
B(pi/2, pi/2)
Maybe it can be simplified.
Good idea, I'm curious!
dario
dario el 29 de Mayo de 2020
Thanks for your support

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by