Append rows of string in a table
7 views (last 30 days)
Show older comments
Sergiu Panainte
on 21 Jul 2020
Commented: Star Strider
on 21 Jul 2020
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?
0 Comments
Accepted Answer
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
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.
.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!