GUI String to Function to evaluate
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Kamuran
am 6 Mai 2015
Beantwortet: Walter Roberson
am 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.
0 Kommentare
Akzeptierte Antwort
Weitere Antworten (1)
Stephen23
am 6 Mai 2015
Bearbeitet: Stephen23
am 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.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Characters and Strings finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!