GUI String to Function to evaluate
1 回表示 (過去 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.
0 件のコメント
採用された回答
その他の回答 (1 件)
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.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Startup and Shutdown についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!