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!

 采纳的回答

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.)

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Data Types 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by