Char to cell array of strings

18 views (last 30 days)
Mike Rovan
Mike Rovan on 4 Nov 2019
Edited: the cyclist on 4 Nov 2019
how do I convert a 1x n char to be split (by the first letter through the last number before the next letter) into cells of an array and become strings
ex
1xn char: BL35.3563.253663.255.25622BL52.53532.1515.45354.2BL343545.454.3.215.1
to become 1x3 cell aray
BL35.3563.253663.255.25622
BL52.53532.1515.45354.2
BL343545.454.3.215.1
(each to be a string in the cell array)

Accepted Answer

the cyclist
the cyclist on 4 Nov 2019
Edited: the cyclist on 4 Nov 2019
output = regexp(c,'BL[\d.]*','match');
where c is your input character array.
That will actually give a cell array of character arrays. If you want to convert that to a cell array of strings, then
output2 = string(output);
  2 Comments
the cyclist
the cyclist on 4 Nov 2019
Sure. You might want to take a look at the documentation for regexp. For all but the simplest cases, I usually have to remind myself of how to identify different patterns. In fact, I found a simpler way to do it for your case, so I edited my answer, and explain the reasoning below. (The prior code would also have spuriously found patterns with commas, because got part of the syntax wrong!)
First step was to conceptually identify the pattern you were going for. I determined that it was "The character BL, followed by any combination of numerals and periods". (At first I thought we might need to use the exact count of periods, but you'll see we don't,)
I'll work "inside out". First,
\d
identifies a single numeric character -- the digits 0-9. Then,
[\d.]
identifies a numeric character or a period. Then,
[\d.]*
identifies any number of numeric characters and periods in a sequence. Finally,
BL[\d.]*
identifies the full pattern: 'BL' followed by any number numeric characters and periods.
I hope that helps! It gets tricky!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!