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.

采纳的回答

Paul
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
ans = 6×1 cell array
{'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'};
% get the desired indices a three element cell array
cellofindices = arrayfun( @(pat)(find(contains(FileNames,pat))),p2(:),'UniformOutput',false)
cellofindices = 3×1 cell array
{[1 2]} {[3 5]} {[4 6]}
% might be easier to use if the indices are stored in a structure
s = cell2struct(cellofindices,p2,1)
s = struct with fields:
S0A: [1 2] S0B: [3 5] S0C: [4 6]

更多回答(1 个)

Fangjun Jiang
Fangjun Jiang 2022-1-27
编辑:Fangjun Jiang 2022-1-27
>> cell2mat(regexp(FileNames,'S0A|S0B|S0C'))
ans =
13 13 13 13 13 13
  1 个评论
Ander Del Olmo Sanz
Sorry, but it does not give me the position por each indicator a previusly mention, so I can extract all names for one indicator.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Cell Arrays 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by