Append rows of string in a table

13 次查看(过去 30 天)
Imagine the following table:
id = {1; 1; 2; 2; 3};
someStr = {"how are"; "you"; "I am"; "fine"; "some text" };
T = table(id, someStr);
What I am trying to do is to append lines with same id. In the end the table must look like this:
idNew = {1; 2; 3};
someStrNew = {"how are you"; "I am fine"; "some text"};
Tnew = table(idNew, someStrNew);
Is there a way to do this in matlab?

采纳的回答

Star Strider
Star Strider 2020-7-21
I can get it to work with character arrays, however not with string objects. I cannot get the char (or similar functions, such as convertStringsToChars) conversion from string objects to character arrays to work inside these functions.
Try this:
id = {1; 1; 2; 2; 3};
% someStr = {"how are"; "you"; "I am"; "fine"; "some text" }; % Commented Out
someStr = {'how are'; 'you'; 'I am'; 'fine'; 'some text' };
Out = accumarray([id{:}]', (1:numel(id))', [], @(x){someStr(x)'});
Out = cellfun(@(x)strjoin(x), Out, 'Uni',0)
producing:
Out =
3×1 cell array
{'how are you'}
{'I am fine' }
{'some text' }
You would likely have to extract everything from the table first. Using table objects have their advantages, however here they simply introduce an additional level of complexity.
  2 个评论
Sergiu Panainte
Sergiu Panainte 2020-7-21
Thank you so much, it worked!
Yeah, extracting from table helped me...although at the end I need a table, for temporary results it was quite helpful
Star Strider
Star Strider 2020-7-21
As always, my pleasure!
It is straightforward to create the results as a table after doing the concatenations. Doing them in the table makes it considerably more difficult.
.

请先登录,再进行评论。

更多回答(0 个)

标签

Community Treasure Hunt

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

Start Hunting!

Translated by