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

8 次查看(过去 30 天)
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!!

采纳的回答

Stephen23
Stephen23 2020-5-18
编辑:Stephen23 2020-5-18
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 个评论
Judith Voortman
Judith Voortman 2020-5-18
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?

请先登录,再进行评论。

更多回答(2 个)

Sulaymon Eshkabilov
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
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

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by