How do I evaluate a function within a string such as 'sin(x)' for given x values?

I am making a program which allows for user input of different functions. I made a dialog box with inputdlg, but the result was a string and I cant figure out how to evaluate the given function numerically.
This is the input part of the code so far. What am I doing wrong?
func=inputdlg('Input Function: y=') func1=str2num(func)
I have also tried using eval()
func=inputdlg('Input Function: y=') func1=eval(func)
My goal is that when someone inputs sin(x), the result is func='sin(x)' and func1 is sin(x) evaluated for the x-values.
Thanks!

 Respuesta aceptada

This will get you started:
func = inputdlg('Input function y = ')
fh = str2func(char(func))
y = fh(pi/6)
The str2func function is under ‘Function Handles’ in the documentation. (I had to search for it.)

Más respuestas (0)

Categorías

Más información sobre Data Types en Centro de ayuda y File Exchange.

Preguntada:

el 1 de Mayo de 2014

Respondida:

el 1 de Mayo de 2014

Community Treasure Hunt

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

Start Hunting!

Translated by