How can I check if a cell array contains multiple strings without loops ?

조회 수: 19 (최근 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
Ander Del Olmo Sanz 2022년 1월 30일
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