equivalent of "a(b==1,:) = 3" for cellarray
이전 댓글 표시
Hello, I am looking for a search of cellarrays that works in the same way as:
a(b==1,:) = 3.
so ideally it would be
a(b=='*name*',:) = 3.
I have a cellarray with a list of participant names and I want to replace the names with numbers. I cannot search for absolute values, as names vary throughout different tests, e.g.Thomas1, Thomas2....
b = {'a' 'P1a'; 'b' 'P1b'; 'c' 'P1a'; 'd' 'P2asdf'; 'e' 'P2sd'; 'f' 'P3hm' };
and the result i want to get is:
a = [1; 1; 1; 2; 2; 3];
답변 (2개)
Azzi Abdelmalek
2016년 7월 6일
b= {'a' 'P1a'; 'b' 'P1b'; 'c' 'P1a'; 'd' 'P2asdf'; 'e' 'P2sd'; 'f' 'P3hm' }
a=str2double(regexp(b(:,2),'\d+','match','once'))
"I have to loop over every possible name."
>> C = {'anna1';'bob2';'chaz1';'anna2';'X';'Y'}
C =
'anna1'
'bob2'
'chaz1'
'anna2'
'X'
'Y'
>> name = {'anna','bob','chaz'};
>> rgx = strcat('\w*',name,'\w*');
>> rpl = arrayfun(@num2str,1:numel(name),'uni',0);
>> regexprep(C,rgx,rpl)
ans =
'1'
'2'
'3'
'1'
'X'
'Y'
댓글 수: 3
Hanne Stenzel
2016년 7월 6일
>> C = {'anna1';'bob2';'chaz1';'anna2';'Teo Georg';'X';'Y'};
>> name = {'anna','bob','chaz','Teo'};
>> rgx = strcat('\w*',name,' ?\w*');
>> rpl = arrayfun(@num2str,1:numel(name),'uni',0);
>> regexprep(C,rgx,rpl,'ignorecase')
ans =
'1'
'2'
'3'
'1'
'4'
'X'
'Y'
Note that regular expressions are very pernickety things: they require careful design to make them work properly. They are not intelligent: they will only match exactly what they have been told to match. This means that you are responsible for knowing exactly what name patterns need to be matched, how these patterns are to be recognized, and then how to encode this in a regular expression.
I can't know if the regular expression above will work for all of your names, because I don't have all of your names, and I don't know what they could contain: space characters, leading or trailing numbers, capitals, lower case, etc, etc... all of these make a difference to regular expressions, but without knowing all of the permitted name styles and string formatting then I cannot say exactly what will work for your strings. The best I can do is to give you a solution that works for the examples that you have given us. Please ask here if you have any questions about regular expressions, or try my FEX submission for experimenting with regular expressions:
Hanne Stenzel
2016년 7월 7일
카테고리
도움말 센터 및 File Exchange에서 Spectral Measurements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!