% Matlab program to demonstrate switch case function
x = 3.0; % numeric variable for length
units = 'cm'; % string variable for unit
switch units
case {'in','inch'} % case 1 if unit is inch
y = 2.54*x; % converts to centimeters
disp ([num2str(x) ' ' units ' converted to cm is :' num2str(y)])
% disp is used to print pretty in the command window
% in the above a string vector is being printed
case {'m','meter'} % case 2 unit is meter
y = x*100; % converts to centimeters
disp ([num2str(x) ' ' units ' converted to cm is :' num2str(y)])
case { 'millimeter','mm'} % case 3 unit is millimeter
y = x/10;
disp ([num2str(x) ' ' units ' converted to cm is :' num2str(y)])
case {'cm','centimeter'} % case 4 unit is centimeter
y = x;
disp ([num2str(x) ' ' units ' converted to cm is :' num2str(y)])
otherwise % for all other cases
disp (['unknown units:' units])
y = nan; % not a number
end
x = 3.0; % numeric variable for length
units = 'cm'; % string variable for unit
switch units
case {'in','inch'} % case 1 if unit is inch
y = 2.54*x; % converts to centimeters
disp ([num2str(x) ' ' units ' converted to cm is :' num2str(y)])
% disp is used to print pretty in the command window
% in the above a string vector is being printed
case {'m','meter'} % case 2 unit is meter
y = x*100; % converts to centimeters
disp ([num2str(x) ' ' units ' converted to cm is :' num2str(y)])
case { 'millimeter','mm'} % case 3 unit is millimeter
y = x/10;
disp ([num2str(x) ' ' units ' converted to cm is :' num2str(y)])
case {'cm','centimeter'} % case 4 unit is centimeter
y = x;
disp ([num2str(x) ' ' units ' converted to cm is :' num2str(y)])
otherwise % for all other cases
disp (['unknown units:' units])
y = nan; % not a number
end
No comments:
Post a Comment