MATLAB: Get Equation as Input from User (str2func)

equation inputevalstr2func

I'm using matlab guide to set up a fairly basic UI for real time graphing and I would like to be able to get equations from users during run time which I will then apply to the values in my graph.
There have been several posts about using eval(stringExpression) or str2func(stringExpression) to convert a stringExpression into a function. However, the relevant posts are all from several years back so I'm wondering what is the best way to parse a string into a matlab function and if there are examples.
Unfortunately looking up the str2func and eval documentation, hasn't given me a good sense about what are acceptable input values to the two functions. If anyone knows where to find more examples that would be very helpful. Thank you!

Best Answer

You don’t need eval with str2func. (Contrary to popular belief, eval has its uses. However it is good practice to avoid it unless absolutely necessary.)
I’m not certain what you want to know about str2func. This example may be informative:
sc = inputdlg('Type an expression that is a function of ‘x’:' ); % Cell Output
s = sc{:}; % Function String
s_fun = str2func(['@(x)' s]) % Not Vectorized (Illustration Only)
s_funv = str2func(['@(x)' vectorize(s)]) % Vectorized
x = linspace(0, 10, 25);
figure(1)
plot(x, s_funv(x), '-p')
grid
It is important to vectorize your functions to be certain that they work with vectors if you want them to work with vectors (necessary for plotting them). The vectorize function offers this capability, so I always use it with str2func to avoid unpleasant surprises and errors about dimensions not agreeing.
Beyond that, once you have created the function with str2func, you can use it just as you would any other function.
Enter x^2*sin(x) in the input dialogue box to see how it works.