MATLAB内置菜单功能

时间:2014-02-16 18:12:40

标签: matlab

任何人都可以给我提示如何使用Matlab内置菜单功能来计算圆柱体,周期和矩形等区域,而无需在脚本中打印菜单选项吗?谢谢。

例如,下面的脚本计算区域但打印出菜单选项

%areaMenu
%this script asks the user for a type of area 
%and prints the area using if-else
%units are assumed to be inches
%display a menu
disp('Menu');
disp('1. Cylinder');
disp('2. Circle');
disp('3. Rectangle');
%choice selection
i=input('Please select your choice now: ');
if i==1
    disp('well! your choice is cylinder');
r=input('enter radius: ');
%error check
if (r<=0)
    disp('Error! Please enter a positive number')
    r=input('enter radius again: ');
end
l=input('enter length: ');
%error check
if l<=0
    disp('Error! Please enter a positive number')
    l=input('enter length again: ');
end
%area calculated and print
%assume the cylinder is closed both sides
area=2*pi*r*r+2*pi*r*l;
fprintf('The area is %.2f\n',area);
elseif i==2
    disp('well! your choice is cycle')
r=input('enter radius: ');
%error check
 if (r<=0)
    disp('Error! Please enter a positive number')
    r=input('enter radius again: ');
end
%area calculated and print
area=pi*r*r;
fprintf('The area is %.2f\n',area);
elseif i==3
    disp('well! your choice is rectangle')
l=input('enter length: ');
%error check
if l<=0
    disp('Error! Please enter a positive number')
    l=input('enter length again: ');
end
w=input('enter width: ');
%error check
if w<=0
    disp('Error! Please enter a positive number')
    w=input('enter width again: ');
end
%area calculated and print
area=l*w;
fprintf('The area is %.2f\n',area);
else
fprintf('invalid choice! Enter a valid choice next time');
end
end

1 个答案:

答案 0 :(得分:0)

使用内置功能就像替换它一样简单:

disp('Menu');
disp('1. Cylinder');
disp('2. Circle');
disp('3. Rectangle');
%choice selection
i=input('Please select your choice now: ');

用这个:

i = menu('Choose shape', 'Cylinder', 'Circle', 'Rectangle');

或者,使用单元格数组:

shapes = {'Cylinder', 'Circle', 'Rectangle'};
i = menu('Choose shape', shapes);

此外,menu可确保选择有效的号码,因此您不再需要检查代码。