How to slice each string in a string array without using for loop
Show older comments
For a string array, for example,
celldata =
3×1 cell array
{'2018-12-12'}
{'2018-11-05'}
{'2018-09-02'}
Is there array operation (i.e. without using for loop) to extract the months from each cell and convert them to a 3*1 numeric matrix, which should be [12;11;09]. I don't want to use for loop because it was too slow.
Accepted Answer
More Answers (4)
Christopher Wallace
on 19 Sep 2018
chardata = cell2mat(a);
numdata = str2num(chardata(:,6:7));
1 Comment
Cedric
on 19 Sep 2018
No, I am CW ;-)
str2double(regexp(celldata,'(?<=-)\d+(?=-)','match','once'))
ans =
12
11
9
Star Strider
on 19 Sep 2018
celldata = [{'2018-12-12'}
{'2018-11-05'}
{'2018-09-02'}];
dt = datetime(celldata);
M = month(dt)
M =
12
11
9
Akira Agata
on 19 Sep 2018
Another possible solution:
celldata = [{'2018-12-12'}
{'2018-11-05'}
{'2018-09-02'}];
M = extractBetween(celldata,'-','-');
M = cellfun(@str2double,M);
Categories
Find more on Data Type Conversion 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!