2016-10-09 39 views
0

我這樣我創建了一個matlab函數,其輸入是數學表達式及其參數。我如何爲我的功能創建一個GUI?

formula = @(a,b) a+b ; 

我用 「公式」 作爲參數傳遞給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 

我怎樣才能解決我的問題?

回答

0

get(handles.edit1,'String')的結果不是一個函數,它的一個char數組。你應該把它轉換成一個函數:

formula=str2func(['@(a,b)' get(handles.edit1,'String')]) 
+0

非常感謝你,你解決了我的問題。只有一個小的修正:get(handles.edit1,'String')])返回一個單元格,所以在str2func()之前,我們把:formula = formula {1};然後:formula = str2func(formula); – xontas

相關問題