Append rows of string in a table

8 views (last 30 days)
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?

Accepted Answer

Star Strider
Star Strider on 21 Jul 2020
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 Comments
Sergiu Panainte
Sergiu Panainte on 21 Jul 2020
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 on 21 Jul 2020
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.
.

Sign in to comment.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!