How do I split cells in an array and save data into a bigger cell array?

10 views (last 30 days)
Hi,
I have a cell array of 20x1, with each cell containing information that I need to split up in 10 strings. How to I make a new array of 20x10, containing all the information?
arr = {'hello i welcome you';'what is your name';'nice to meet you'};
output = { 'hello','i','welcome','you';'what','is','your','name';'nice','to','meet','you'};
I tried the following:
for i = 1:size(arr,1)
intercept = char(arr(i,:));
newarr{i,:} = strsplit(intercept,' ');
end
But this just leaves me with a 20x1 cell array, containing 20 1x10 cell arrays.
Thanks guys!!

Accepted Answer

Stephen23
Stephen23 on 18 May 2020
Edited: Stephen23 on 18 May 2020
Use a comma-separated list to help concatenate them into one cell array or string array:
>> arr = {'hello i welcome you';'what is your name';'nice to meet you'};
>> out = regexp(arr,'\w+','match');
>> out = [out{:}]; % comma-separated list
>> size(out)
ans =
1 12
Checking the contents:
>> out{:}
ans = hello
ans = i
ans = welcome
ans = you
ans = what
ans = is
ans = your
ans = name
ans = nice
ans = to
ans = meet
ans = you
See also:
  2 Comments
Judith Voortman
Judith Voortman on 18 May 2020
Halfway there! But I do need columns and vectors, as I'm working with a table (e.g. i would want to know the first word of every sentence). Can i transform this into a 4x3 cell?

Sign in to comment.

More Answers (2)

Sulaymon Eshkabilov
Sulaymon Eshkabilov on 18 May 2020
Here is one of the possible solutions:
arr = {'hello i welcome you';'what is your name';'nice to meet you'};
output = { 'hello','i','welcome','you';'what','is','your','name';'nice','to','meet','you'};
for i = 1:length(arr)
intercept = char(arr(i,:));
newdata{i,:} = strsplit(intercept, {' ', ','},'CollapseDelimiters',true);
end

Sulaymon Eshkabilov
Sulaymon Eshkabilov on 18 May 2020
Here is the alternative solution:
arr = {'hello i welcome you';'what is your name';'nice to meet you'};
for i = 1:length(arr)
intercept = char(arr(i,:));
newdata(i,:) = strsplit(intercept, {' ', ','},'CollapseDelimiters',true);
end
for ii=1:length(newdata)
for jj=1:length(newdata{1})
output(ii, jj)=newdata{ii}(jj);
end
end

Categories

Find more on Matrices and Arrays 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!