matlab says the inline function will be removed in future release how should i execute a string function like '2*x.^2+5'

function

1 comentario

When you read the inline documentation the very first line of text says:
inline will be removed in a future release. Use Anonymous Functions instead.
How about using anonymous functions, just like the documentation recommends?

Iniciar sesión para comentar.

 Respuesta aceptada

Your function becomes:
fcn = @(x) 2*x.^2+5;
the call it as you would any other function:
y = fcn(x);
To convert a string to a function, use the str2func (link) function:
str = '2*x.^2+5';
fun = str2func(['@(x) ',str]);
y = fun(x);
This creates the anonymous function from the string, and returns a function handle.

6 comentarios

omid
omid el 21 de Jun. de 2017
Editada: omid el 21 de Jun. de 2017
Sorry I have another question If my string be different in variable for every equation and I have to use a handle for variable for example k=char(symvar(2*y^2+3) then i want to use your solution, it give me an error f=str2func(['@(k)','2*y^2+3') Is there way to use handle for variable?
Aaahh, the old X-Y problem again. See Andrei Bobrov's answer for the correct way to handle this.
@omid — My pleasure.
If you are using symbolic variables and functions, use the Symbolic Math Toolbox matlabFunction function.
Use the symvar function to identify the variable(s) and use the char vector it returns in defining the char vector you pass into str2func.
Thanks for these comments. They are very useful for computational math.

Iniciar sesión para comentar.

Categorías

Más información sobre Function Creation en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 20 de Jun. de 2017

Comentada:

el 29 de Jun. de 2021

Community Treasure Hunt

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

Start Hunting!

Translated by