matlab 中 switch 的例子

来源:学生作业帮助网 编辑:作业帮 时间:2024/05/05 15:53:05

matlab 中 switch 的例子
matlab 中 switch 的例子

matlab 中 switch 的例子
Programming in MATLAB: Switch/Case Statement - Code
x = 3.0; % numeric variable
units = 'mm'; % string variable
switch units
case {'in','inch'} % multiple matches
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'}
y = x*100; % converts to centimeters
disp ([num2str(x) ' ' units ' converted to cm is :' num2str(y)])
case { 'millimeter','mm'}
y = x/10;
disp ([num2str(x) ' ' units ' converted to cm is :' num2str(y)])
case {'cm','centimeter'}
y = x;
disp ([num2str(x) ' ' units ' converted to cm is :' num2str(y)])
otherwise
disp (['unknown units:' units])
y = nan; % not a number
end