Borrar filtros
Borrar filtros

Converting string to function/number

9 visualizaciones (últimos 30 días)
Luqman Hadiwinata
Luqman Hadiwinata el 26 de Mayo de 2022
Comentada: Luqman Hadiwinata el 2 de Jun. de 2022
Hello, sorry to bother your time. So in this case, my problem is, i'm trying to design an app using app designer that can take user input in string and convert it into numbers. However, when i try to use some mathematical function like 'sin, cos, exp' etc, as an input, i want those strings to be converted into the mathematical function as they were stated. How can i achieve this?
  2 comentarios
Stephen23
Stephen23 el 27 de Mayo de 2022
Editada: Stephen23 el 27 de Mayo de 2022
"How can i achieve this?"
If you are interested in writing debuggable, robust, secure code and have only a limited number of such functions then use SWITCH or a cell array of explicit function handles or similar.
If you are happy with the risks of allowing the user to be able to run anything then use STR2FUNC.
Luqman Hadiwinata
Luqman Hadiwinata el 2 de Jun. de 2022
Hi Stephen, thank you for your answer. However i still have 1 question, if i want to add a time domain to my function, like:
t = 0:10:20000
rt = exp(t/10000).*cos(pi*t/500)
how can i achive this? by the way, thank you again for your answer

Iniciar sesión para comentar.

Respuestas (3)

Rik
Rik el 26 de Mayo de 2022
The way to avoid eval in this case is to use str2func:
f=str2func('cos');
f(pi)
ans = -1

David Hill
David Hill el 26 de Mayo de 2022
Look at eval function (normally not recommended).
a='cos(1)';
eval(a)

Walter Roberson
Walter Roberson el 27 de Mayo de 2022
str2sym()
matlabFunction is commonly used together with str2sym()

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by