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

8 ビュー (過去 30 日間)
Judith Voortman
Judith Voortman 2020 年 5 月 18 日
コメント済み: Stephen23 2020 年 5 月 19 日
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
  1 件のコメント
Judith Voortman
Judith Voortman 2020 年 5 月 18 日
Still gives me a 20x1 cell array, containing 1x13 cell arrays...

サインインしてコメントする。


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 Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by