read cell array and split into one cell array of multiple rows

Hello,
I have a cell array with strings, for example:
names =
2×1 cell array
{'A B C D E F G H '}
{'I J ' }
I want them in an array like this one:
KNAME =
10×1 cell array
{'A'}
{'B'}
{'C'}
{'D'}
{'E'}
{'F'}
{'G'}
{'H'}
{'I'}
{'J'}
I do something too complicated that works but I am guessing there is an easier solution to this

 채택된 답변

Stephen23
Stephen23 2019년 1월 29일
편집: Stephen23 2019년 1월 29일

2 개 추천

name = {...
'ABCDEFGHIJKLMNOPB C D E F G H';...
'I J '};
kname = regexp(name,'\w{1,16}','match');
kname = [kname{:}].'
Giving:
>> kname{:}
ans = ABCDEFGHIJKLMNOP
ans = B
ans = C
ans = D
ans = E
ans = F
ans = G
ans = H
ans = I
ans = J

댓글 수: 3

One more question, what if there is a dot (.) on the name? for example A.BC
I'm just trying to do something general, where each name could have any sort of character (letters digits, dot(.)) .I see it works with digits and characters but it doesn't when there is '.' on the name, it splits at the dot. I'm sorry, I hadn't realized it was a special character that is why I hadn't mentioned it originally.
Stephen23
Stephen23 2019년 1월 29일
편집: Stephen23 2019년 1월 29일
To include a period character you can use this regular expression:
'[\w\.]{1,16}'
That will match from 1 to 16 letters, digits, undescores, and periods. The MATLAB documentation explains how regular expressions are defined:
It does take a lot of practice and reading the documentation to get used to regular expressions, so feel free to ask if you want more help.
Thank you!!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Omer Yasin Birey
Omer Yasin Birey 2019년 1월 29일
name{1,:} = {'A B C D E F G H'};
name{2,:} = {'J '};
str = string(name);
C = arrayfun( @(x) strsplit( x, ' ' ), str, 'UniformOutput', false );
conc = horzcat(C{:})';
cellA = cellstr(conc);

댓글 수: 2

Thank you! This works perfectly with my example but I just realized that my original cell array could be like this (I get this array by reading an external file):
names =
2×1 cell array
{'ABCDEFGHIJKLMNOPB C D E F G H '}
{'I J ' }
Each individual name can have up to 16 characters and if it does in that case there is no blank space between that one and the next, (in this new example ABCDEFGHIJKLMNOP and B). Is there a way to set the delimiter as a number of characters instead of a white space?
I'm sorry for not realizing this before
Yes FM, Stephen's answer can do what you want.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품

질문:

FM
2019년 1월 29일

편집:

2019년 1월 29일

Community Treasure Hunt

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

Start Hunting!

Translated by