Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
861 views
in Technique[技术] by (71.8m points)

regex - Convert cell array of cells into cell array of strings in MATLAB

Using regexp with tokens on cell array of strings I've got cell array of cells. Here is simplified example:

S = {'string 1';'string 2';'string 3'};
res = regexp(S,'(d)','tokens')
res = 

    {1x1 cell}
    {1x1 cell}
    {1x1 cell}
res{2}{1}
ans = 
    '2'

I know I have only one match per cell string in S. How I can convert this output into cell arrays of strings in a vectorized form?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is even worse than you thought. Your output from REGEXP is actually a cell array of cell arrays of cell arrays of strings! Yeah, three levels! The following uses CELLFUN to get rid of the top two levels, leaving just a cell array of strings:

cellArrayOfStrings = cellfun(@(c) c{1},res);

However, you can also change your call to REGEXP to get rid of one level, and then use VERTCAT:

res = regexp(S,'(d)','tokens','once');  %# Added the 'once' option
cellArrayOfStrings = vertcat(res{:});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...