Split String in a Table

조회 수: 8 (최근 30일)
Aldrich To
Aldrich To 2015년 11월 10일
댓글: Stephen23 2024년 10월 22일
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
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'});
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
Stephen23
Stephen23 2024년 10월 22일
Num = [1;2;3];
Str = ["a,b,c"; "d,e,f"; "g,h,i"];
tbl = table(Num,Str)
tbl = 3x2 table
Num Str ___ _______ 1 "a,b,c" 2 "d,e,f" 3 "g,h,i"
out = splitvars(convertvars(tbl,@isstring,@(s)split(s,',')))
out = 3x4 table
Num Str_1 Str_2 Str_3 ___ _____ _____ _____ 1 "a" "b" "c" 2 "d" "e" "f" 3 "g" "h" "i"

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by