How can I check if a cell array contains multiple strings without loops ?
20 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Paul
2022-1-30
编辑:Paul
2022-1-30
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)
更多回答(1 个)
Fangjun Jiang
2022-1-27
编辑:Fangjun Jiang
2022-1-27
>> cell2mat(regexp(FileNames,'S0A|S0B|S0C'))
ans =
13 13 13 13 13 13
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Cell Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!