替代matlab中的if elseif

时间:2013-07-05 19:28:07

标签: string matlab if-statement

我有一个名为name的字符串。 name中的第三个字符是一个字母,表示与name关联的月份,根据以下方案:

Jan  F
Feb  G
Mar  H
Abr  J
May  K
Jun  M
Jul  N
Aug  Q
Sep  U
Oct  V
Nov  X
Dec  Z

我想重命名name标识的文件,以便使用数字代替任意字母系统:

01
02
 ...
12

为此,我以下列方式使用if / elseif:

 if name(3) == 'F'                      
            monthdesignator = '01';
        elseif name(3) == 'G'
            monthdesignator = '02';
        elseif name(3) == 'H'
            monthdesignator = '03';
        elseif name(3) == 'J'
            monthdesignator = '04';
        elseif name(3) == 'K'
            monthdesignator = '05';
        elseif name(3) == 'M'
            monthdesignator = '06';
        elseif name(3) == 'N'
            monthdesignator = '07';
        elseif name(3) == 'Q'
            monthdesignator = '08';
        elseif name(3) == 'U'
            monthdesignator = '09';
        elseif name(3) == 'V'
            monthdesignator = '10';
        elseif name(3) == 'X'
            monthdesignator = '11';
        else
            monthdesignator = '12';   
        end

 newfilename=strcat('C:\TickDataMinuteBars\MinuteBarsCsv\',name(1),name(2),'20',name(4),name(5),monthdesignator,'.csv');

但这是如此笨拙和重复。有更优雅的方式吗?

2 个答案:

答案 0 :(得分:6)

选项1:使用hashmap(此选项最快,最简洁):

% Define your table once.
keys = {'F','G','H','J','K','M','N','Q','U','V','X','W'};
values = {'01','02','03','04','05','06','07','08','09','10','11','12'};
lookup = containers.Map(keys,values,'UniformValues', true);

% Lookups run in constant O(1) time.
month = lookup(name(3));

选项2 :使用case statements,稍微好于if/else

switch name(3)
  case 'F', month = '01';
  case 'G', month = '02';
  case 'H', month = '03';
  ...
  otherwise, month = '12';
end

答案 1 :(得分:1)

实际上matlab中有一个switch-case语句。你可以阅读它here