GUI String to Function to evaluate

2 views (last 30 days)
Hello,
I am asking user to input a function with variable x using GUI. User inputs F= x^5+sin(x)*x+1 (example) and I would like to use this string as function input and evaluate x=[0 1 4 6 9 10] (example) but
% get(hObject,'String') returns contents of edit3 as text % str2double(get(hObject,'String')) returns contents of edit3 as a double.
This does not work. I was hoping str2func would work but no. I know that I can predefine x, and ask user to input F=x.^5 + sin(x).*x+ 1 but that is not the way I want to do it. I want inputting as natural as possible without user thinking about matrix power or size matching issue.
Is there a way to do it ?
Thanks.

Accepted Answer

Walter Roberson
Walter Roberson on 6 May 2015
Use vectorize on the string version of the edit field, and the str2func() the result.

More Answers (1)

Stephen23
Stephen23 on 6 May 2015
Edited: Stephen23 on 6 May 2015
If you want the code "...without user thinking about matrix power or size matching...", then it may be simplest to evaluate the function using arrayfun, which would allow the function to be defined only for a scalar value x, and not a vector. And we can easily construct an anonymous function using str2func, so the code could look something like this:
>> str = 'x^5+sin(x)*x+1';
>> fun = str2func(['@(x)',str]);
>> X = [0,1,4,6,9,10];
>> arrayfun(fun,X)
ans =
1.0e+04 *
0.0001 0.0003 0.1022 0.7775 5.9054 9.9996
This also has the advantage that it also works if the user knows MATLAB and enters the function using array-notation.

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!