Clear Filters
Clear Filters

Efficient splitting of strings

4 views (last 30 days)
Hamad Alsayed
Hamad Alsayed on 21 Mar 2016
Commented: Hamad Alsayed on 21 Mar 2016
I have a cell array of strings which I would like to split into sub-arrays as follows:
Suppose a date-time cell array reads as:
inputArray =
'20150316 07:20:39:380941'
'20150317 07:20:39:380941'
'20150318 07:20:39:380941'
'20150319 07:20:39:380941'
I would like the output to be
outputArray =
'20150316'
'20150317'
'20150318'
'20150319'
Currently I am doing it by
outputArray = cellfun(@(x) x(1:8),inputArray,'uni',false);
which works just fine, however for inputArray into the millions of elements, this process is slow.
Is there a more efficient method which can perform the above? I know for sure that the structure of the strings in the array is fixed (i.e. the string length is always 24 and the first 8 elements are YYYYMMDD).

Accepted Answer

KSSV
KSSV on 21 Mar 2016
You can read all the strings into a character matrices and extract what you want. Example:
k = ['20150316 07:20:39:380941'
'20150317 07:20:39:380941'
'20150318 07:20:39:380941'
'20150319 07:20:39:380941'];
k(:,1:9)
Have you tried this?
  1 Comment
Hamad Alsayed
Hamad Alsayed on 21 Mar 2016
That is perfect, Siva. Thank you. Even after "cellstr"-ing the answer back, execution time is cut by more than a half. Thanks again! Hamad.

Sign in to comment.

More Answers (0)

Categories

Find more on Characters and Strings 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!