equivalent of "a(b==1,:) = 3" for cellarray
Show older comments
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];
Answers (2)
Azzi Abdelmalek
on 6 Jul 2016
b= {'a' 'P1a'; 'b' 'P1b'; 'c' 'P1a'; 'd' 'P2asdf'; 'e' 'P2sd'; 'f' 'P3hm' }
a=str2double(regexp(b(:,2),'\d+','match','once'))
1 Comment
Hanne Stenzel
on 6 Jul 2016
"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 Comments
Hanne Stenzel
on 6 Jul 2016
>> 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
on 7 Jul 2016
Categories
Find more on Spectral Measurements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!