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 CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by