matlab 加法器,Matlab GUI编程实例(加法器)

布置好各控件以后,我们就可以来为这些控件编写程序来实现两数相加的功能了。

三.我们先为数据1文本框添加代码;

1f1d56d708fe93b5573c95bf089c3b2f.png

点击上图所示红色方框,选择edit1_Callback,或者是在数据1文本框出右键选择View Callbacks–>Callback,光标便立刻移到下面这段代码的位置:

function edit1_Callback(hObject, eventdata, handles)

% hObject handle to edit1 (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit1 as text

% str2double(get(hObject,'String')) returns contents of edit1 as a double

然后在上面这段代码的下面插入如下代码:

input=str2num(get(hObject,'String'));

if (isempty(input))

set(hObject,'String','0');

end

guidata(hObject,handles);

这段代码使得输入被严格限制,我们不能试图输入一个非数字。

四.为edit2_Callback添加同样一段代码。

五.现在我们为计算按钮添加代码来实现把数据1和数据2相加的目的。用上面三的同样的方法在m文件中找到pushbutton1_Callback代码段如下:

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)

% a and b are variables of strings type,and needs to be converted 在上面这段代码后添加以下代码: