GUI String to Function to evaluate

2 vues (au cours des 30 derniers jours)
Kamuran
Kamuran le 6 Mai 2015
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.

Réponse acceptée

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

Plus de réponses (1)

Stephen23
Stephen23 le 6 Mai 2015
Modifié(e) : Stephen23 le 6 Mai 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.

Catégories

En savoir plus sur Startup and Shutdown dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by