我创建了一个 matlab 函数,其输入是数学表达式及其参数。如何为我的函数创建 GUI?
I created a matlab function which inputs are the mathematical expression and their parameters. How can I create a GUI for my function?
我这样定义了一个数学函数
formula = @(a,b) a+b ;
我使用 "formula" 作为 matlab 函数的参数:
function result = myfunction(formula,a,b)
result = formula(a,b);
end
一切正常
formula = @(a,b) a+b ;
result=myfunction(formula,3,2)
result =
5
但我的目标是创建一个 GUI,所以我尝试了以下操作:
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
formula=get(handles.edit1,'String');
a=str2double(get(handles.edit2,'String'))
b=str2double(get(handles.edit3,'String'))
result = formula(a,b);
set(handles.text1,'string',result);
但我得到这个错误:
Index exceeds matrix dimensions.
Error in untitled>pushbutton1_Callback (line 86)
result = formula(a,b);
Error in gui_mainfcn (line 95)
feval(varargin{:});
Error in untitled (line 42)
gui_mainfcn(gui_State, varargin{:});
Error in @(hObject,eventdata)untitled('pushbutton1_Callback',hObject,eventdata,guidata(hObject))
Error while evaluating uicontrol Callback
我该如何解决我的问题?
get(handles.edit1,'String')
的结果不是一个函数,它是一个 char
数组。您应该将其转换为函数:
formula=str2func(['@(a,b)' get(handles.edit1,'String')])
我这样定义了一个数学函数
formula = @(a,b) a+b ;
我使用 "formula" 作为 matlab 函数的参数:
function result = myfunction(formula,a,b)
result = formula(a,b);
end
一切正常
formula = @(a,b) a+b ;
result=myfunction(formula,3,2)
result =
5
但我的目标是创建一个 GUI,所以我尝试了以下操作:
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
formula=get(handles.edit1,'String');
a=str2double(get(handles.edit2,'String'))
b=str2double(get(handles.edit3,'String'))
result = formula(a,b);
set(handles.text1,'string',result);
但我得到这个错误:
Index exceeds matrix dimensions.
Error in untitled>pushbutton1_Callback (line 86)
result = formula(a,b);
Error in gui_mainfcn (line 95)
feval(varargin{:});
Error in untitled (line 42)
gui_mainfcn(gui_State, varargin{:});
Error in @(hObject,eventdata)untitled('pushbutton1_Callback',hObject,eventdata,guidata(hObject))
Error while evaluating uicontrol Callback
我该如何解决我的问题?
get(handles.edit1,'String')
的结果不是一个函数,它是一个 char
数组。您应该将其转换为函数:
formula=str2func(['@(a,b)' get(handles.edit1,'String')])