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

6 visualizaciones (últimos 30 días)
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!!

Respuesta aceptada

Stephen23
Stephen23 el 18 de Mayo de 2020
Editada: Stephen23 el 18 de Mayo de 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 comentarios
Judith Voortman
Judith Voortman el 18 de Mayo de 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?
Stephen23
Stephen23 el 19 de Mayo de 2020
"Can i transform this into a 4x3 cell?"
out = reshape(out,3,4).'

Iniciar sesión para comentar.

Más respuestas (2)

Sulaymon Eshkabilov
Sulaymon Eshkabilov el 18 de Mayo de 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 el 18 de Mayo de 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

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by