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?
Stephen23
Stephen23 2020년 5월 19일
"Can i transform this into a 4x3 cell?"
out = reshape(out,3,4).'

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

추가 답변 (2개)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2020년 5월 18일
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 2020년 5월 18일
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