在Matlab的命令行窗口,可以直接进行四则运算,也就是加减乘除。这里,我们换一种路径,改在GUI里实现四则运行,如图(1)所示:
1)打开Matlab,点击工具栏上的【File】–》New–》GUI,命名为:addnum.fig
2)在addnum.fig面板里,拖曳6个静态文本TXT控件、6个编辑框EDIT控件、4个按钮,6个EDIT控件的String属性值0,分别设置编辑框、按钮的String属性和Tag属性。如表(1)所示:
String | Tag | |
编辑框a | 0 | edit_a |
编辑框b | 0 | edit_b |
编辑框a+b | 0 | edit_sum |
编辑框a-b | 0 | edit_sub |
编辑框a*b | 0 | edit_cheng |
编辑框a/b | 0 | edit_chu |
按钮[求和] | 求和 | addNum |
按钮[求差] | 求差 | subNum |
按钮[求积] | 求积 | chengNum |
按钮[求商] | 求商 | chuNum |
3)编写4个按钮的Callback代码
%%addnum.m
%%相加
function addNum_Callback(hObject, eventdata, handles)
a = str2num(get(handles.edit_a,'String'));
b = str2num(get(handles.edit_b,'String'));
c = a+b;
str = num2str(c);
set(handles.edit_sum,'String',str);
%%相减
function subNum_Callback(hObject, eventdata, handles)
a2 = str2num(get(handles.edit_a,'String'));
b2 = str2num(get(handles.edit_b,'String'));
c2 = a2-b2;
str2 = num2str(c2);
set(handles.edit_sub,'String',str2);
%%相乘
function chengNum_Callback(hObject, eventdata, handles)
a2 = str2num(get(handles.edit_a,'String'));
b2 = str2num(get(handles.edit_b,'String'));
c2 = a2*b2;
str2 = num2str(c2);
set(handles.edit_ji,'String',str2);
%%相除
function chuNum_Callback(hObject, eventdata, handles)
a2 = str2num(get(handles.edit_a,'String'));
b2 = str2num(get(handles.edit_b,'String'));
if ( b2~=0)
c2 = a2/b2;
str2 = num2str(c2);
set(handles.edit_shang,'String',str2);
else
%disp('除数为0')
errordlg('除数不能为0!');
end
4)在MatLab的命令行窗口,输入:addnum,弹出Untitled对话框,输入相应的数字,就可以进行加减乘除了。注意不要点击.fig文件,该文件只是资源文件,真正执行命令的文件是.m文件(脚本文件或函数文件)。如图(2)所示:
详细代码,请看:
http://download.csdn.net/detail/sanqima/9302393
来源:CSDN
作者:sanqima
链接:https://blog.csdn.net/sanqima/article/details/50032491