GUI String to Function to evaluate

8 次查看(过去 30 天)
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.

采纳的回答

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

更多回答(1 个)

Stephen23
Stephen23 2015-5-6
编辑:Stephen23 2015-5-6
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.

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by