How can I check if a cell array contains multiple strings without loops ?
20 views (last 30 days)
Show older comments
Ander Del Olmo Sanz
on 27 Jan 2022
Commented: Ander Del Olmo Sanz
on 31 Jan 2022
Hi, I have a cell array (1x198) in which every cell contains a string. Each of this string is the name of a test (20-MAG-C-Z1-S0A) and they have an indicator inside de name (S0A,S0B,S0C). For each of them, I want to extrat the position of the string that contain the mentionen indicator, but without a loop, since in same cases i could have more than 100000 tests. The Matlab verison I am using is Matlab R2021b.
I have been trying with different methods to solve it and the most promising was applying cellfun().
FileNames={'20-MAG-C-Z1-S0A','20-MAG-C-Z2-S0A','20-MAG-C-Z1-S0B','20-MAG-C-Z3-S0C','20-MAG-C-Z2-S0B','20-MAG-C-Z1-S0C',....};
p2={'S0A','S0B','S0C'};
index = cellfun(@(c) strcmp(c,FileNames),p2,'UniformOutput',false);
for this case I have obtained 1x3 cell array with 1x198 logical inside him and they are complete empty with no position of the indicator as it should be since 'S01' is no '20-MAG-C-Z1-
index = cellfun(@(c) contains(c,FileNames),p2,'UniformOutput',false);
S0A'. On the other hand if i try with the funtion contains, it return a 1x3 cell array with zero value in all cells.¿Why? It should not have to return a 1x3 cell array with 1x198 logical inside of each of them indicating the position for each indicator ('S0A','S0B','S0C')
Could you give me some guide lines to follow please? The result I want to obtain is position in a way that a could them later manipulate each document i have.
0 Comments
Accepted Answer
Paul
on 30 Jan 2022
Edited: Paul
on 30 Jan 2022
Assuming that numerical indices are desired (as apposed to logical)
% example data
FileNames={'20-MAG-C-Z1-S0A','20-MAG-C-Z2-S0A','20-MAG-C-Z1-S0B','20-MAG-C-Z3-S0C','20-MAG-C-Z2-S0B','20-MAG-C-Z1-S0C'};
FileNames.' % see what they are
p2={'S0A','S0B','S0C'};
% get the desired indices a three element cell array
cellofindices = arrayfun( @(pat)(find(contains(FileNames,pat))),p2(:),'UniformOutput',false)
% might be easier to use if the indices are stored in a structure
s = cell2struct(cellofindices,p2,1)
More Answers (1)
Fangjun Jiang
on 27 Jan 2022
Edited: Fangjun Jiang
on 27 Jan 2022
>> cell2mat(regexp(FileNames,'S0A|S0B|S0C'))
ans =
13 13 13 13 13 13
See Also
Categories
Find more on Cell Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!