Matching certain characters of strings

1 回表示 (過去 30 日間)
Christiaan
Christiaan 2013 年 2 月 25 日
Say I have a big cell array of strings (they are item numbers), and I want to say:
If string matches '140xx1', then Type = 1,
If string matches '140xx2' then Type = 2,
If string matches '140xx3' then Type = 3,
If string matches '145xxx' then Type = 4,
(where x can be any character).
How can I do this in MATLAB?
Many thanks,
Chris

回答 (4 件)

Thorsten
Thorsten 2013 年 2 月 25 日
item_number_list = { '140xx3' '140xx3' '140xx1' '145xxx' '140xx2' '140xx3'};
item_numbers = {'140xx1' '140xx2' '140xx3' '145xxx'};
for i=1:length(item_number_list)
item_type(i) = find(strcmp(item_numbers, item_number_list{i}));
end
  1 件のコメント
Christiaan
Christiaan 2013 年 2 月 25 日
Thanks, but I don't think this solves the problem. 'x' could appear as any character in the item number list (it could be a '1', an 'A', etc). For example, it could be:
item_number_list = { '140003' '140013' '140001' '145012' '140022' '140123'};
Any more suggestions? I think I may have to use regexp, but I'm not really sure how to make it do this.

サインインしてコメントする。


Thorsten
Thorsten 2013 年 2 月 25 日
Oh, I haven't realized that x were meant as placeholders for any number. In this case, use
item_numbers = {'140xx1' '140xx2' '140xx3' '145xxx'};
item_number_list = { '140003' '140013' '140001' '145012' '140022' '140123'};
for i=1:length(item_number_list)
item = item_number_list{i};
item(4:5) = 'xx';
if item(3) == '5', item(6) = 'x'; end
item_type(i) = find(strcmp(item_numbers, item));
end

Jos (10584)
Jos (10584) 2013 年 2 月 25 日
I seems that only the last character of the string is of importance:
LIST = {'140111','140aa4','999cc3','123ZZ1','145xxx'}
TYPE = cellfun(@(x) x(numel(x))-'0', LIST)
TYPE(~ismember(TYPE,[1 2 3])) = 4

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 2 月 25 日
編集済み: Azzi Abdelmalek 2013 年 2 月 25 日
yourlist={'140221','140214','140111','140223','140544','140773'}
type1=yourlist(cell2mat(cellfun(@(x) ~isempty(regexp(x,'\<140\d\d1\>')),yourlist,'un',0)))
type2=yourlist(cell2mat(cellfun(@(x) ~isempty(regexp(x,'\<140\d\d2\>')),yourlist,'un',0)))
type3=yourlist(cell2mat(cellfun(@(x) ~isempty(regexp(x,'\<140\d\d3\>')),yourlist,'un',0)))
type4=yourlist(cell2mat(cellfun(@(x) ~isempty(regexp(x,'\<140\d\d4\>')),yourlist,'un',0)))

カテゴリ

Help Center および File ExchangeEnvironment and Settings についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by