Split String in a Table
显示 更早的评论
Hello,
I am attempting to split a string in a table. I am not sure what approach I should be taking. Do I convert the table into an array first, use strsplit, and then recombine arrays into a table?
When I try to use table2array, I get the following error: Cannot concatenate the table variables 'Arbitrary', because their types are double and cell.
Thanks!
回答(1 个)
Tejas
2024-10-22
Hello Aldrich,
To split the strings in a column, follow the steps in the example below:
- Make sure the column with strings is a cell array of strings.
T = table([1; 2; 3], {'a,b,c'; 'd,e,f'; 'g,h,i'}, 'VariableNames', {'Numeric', 'StringColumn'});
- Go through each element of the column and store the split strings in a vector. For a better understanding of the 'function handle' used, refer to this documentation: https://www.mathworks.com/help/matlab/ref/function_handle.html .
splitStrings = cellfun(@(x) strsplit(x, ','), T.StringColumn, 'UniformOutput', false);
- Place these split strings into new, separate columns of the table.
maxSplits = max(cellfun(@length, splitStrings));
for i = 1:maxSplits
T.(['Part' num2str(i)]) = cellfun(@(x) x{i}, splitStrings, 'UniformOutput', false);
end
Below is a screenshot of the expected outcome:

1 个评论
Num = [1;2;3];
Str = ["a,b,c"; "d,e,f"; "g,h,i"];
tbl = table(Num,Str)
out = splitvars(convertvars(tbl,@isstring,@(s)split(s,',')))
类别
在 帮助中心 和 File Exchange 中查找有关 Cell Arrays 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!