資源描述:
《編程實(shí)例加法器》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在行業(yè)資料-天天文庫(kù)。
MatlabGUI編程實(shí)現(xiàn)加法器一.首先我們新建一個(gè)GUI文件:,選擇BlankGUI(Default),如下圖所示二.進(jìn)入GUI開(kāi)發(fā)環(huán)境以后添加兩個(gè)編輯文本框,6個(gè)靜態(tài)文本框和一個(gè)按鈕,布置如下圖所示:下載(28.24KB)2009-5-3122:193/33/33
1布置好各控件以后,我們就可以來(lái)為這些控件編寫(xiě)程序來(lái)實(shí)現(xiàn)兩數(shù)相加的功能了。三.我們先為數(shù)據(jù)1文本框添加代碼;點(diǎn)擊上圖所示紅色方框,選擇edit1_Callback,或者是在數(shù)據(jù)1文本框出右鍵選擇ViewCallbacks–>Callback,光標(biāo)便立刻移到下面這段代碼的位置:functionedit1_Callback(hObject,eventdata,handles)%hObjecthandletoedit1(seeGCBO)%eventdatareserved-tobedefinedinafutureversionofMATLAB%handlesstructurewithhandlesanduserdata(seeGUIDATA)%Hints:get(hObject,'String')returnscontentsofedit1astext%str2double(get(hObject,'String'))returnscontentsofedit1asadouble然后在上面這段代碼的下面插入如下代碼:input=str2num(get(hObject,'String'));if(isempty(input))set(hObject,'String','0');endguidata(hObject,handles);這段代碼使得輸入被嚴(yán)格限制,我們不能試圖輸入一個(gè)非數(shù)字。四.為edit2_Callback添加同樣一段代碼。五.現(xiàn)在我們?yōu)橛?jì)算按鈕添加代碼來(lái)實(shí)現(xiàn)把數(shù)據(jù)1和數(shù)據(jù)2相加的目的。用上面三的同樣的方法在m文件中找到pushbutton1_Callback代碼段如下:functionpushbutton1_Callback(hObject,eventdata,handles)%hObjecthandletopushbutton1(seeGCBO)%eventdatareserved-tobedefinedinafutureversionofMATLAB%handlesstructurewithhandlesanduserdata(seeGUIDATA)%aandbarevariablesofstringstype,andneedstobeconverted在上面這段代碼后添加以下代碼:3/33/33
2a=get(handles.edit1,'String');b=get(handles.edit2,'String');total=str2num(a)+str2num(b);%theresultneedstobeconvertedbackintostringtypetodisplayitc=num2str(total);set(handles.text3,'String',c);guidata(hObject,handles);下面我們來(lái)對(duì)上面這段程序分析一下;a=get(handles.edit1,'String');b=get(handles.edit2,'String');上面這行代碼把用戶輸入的數(shù)據(jù)存入到變量a,變量b中;%a,b是字符型變量,在計(jì)算兩者相加之前需把他們轉(zhuǎn)換為數(shù)字型。total=str2num(a)+str2num(b);這段代碼實(shí)現(xiàn)兩數(shù)相加c=num2str(total);set(handles.text3,'String',c);guidata(hObject,handles);以上兩行代碼分別用來(lái)更新計(jì)算結(jié)果文本框和圖形對(duì)象句柄,一般Callback回調(diào)函數(shù)都以guidata(hObject,handles)結(jié)束以更新數(shù)據(jù)。程序運(yùn)行如下:3/33/33