seperating char data at matlab

2 次查看(过去 30 天)
Hello everone,
i have an excell file, i import it matlab environment as table. At the first column, there is a char variable that i want to seperate 2 different column. How can i do that?
thanks

采纳的回答

Image Analyst
Image Analyst 2021-12-26
Try to create two new column cell arrays and put the two words into that, then rebuild the table without the original strings and with the two new string columns. Like:
str = {'abc def'; 'ghi jklmn'; 'xyz 123'};
v1 = rand(3, 1);
v2 = rand(3, 1);
t = table(v1, str, v2)
t = 3×3 table
v1 str v2 _______ _____________ _______ 0.58296 {'abc def' } 0.34595 0.68275 {'ghi jklmn'} 0.43401 0.96797 {'xyz 123' } 0.68611
numRows = height(t);
% Allocate new column vectors that we will put into the table.
word1 = cell(numRows, 1);
word2 = cell(numRows, 1);
for row = 1 : numRows
thisString = t.str(row);
% Parse into words
words = strsplit(char(thisString));
% Put into different columns for the table.
word1{row} = words{1};
word2{row} = words{2};
end
% Create new table with the new columns.
tNew = table(t.v1, t.v2, word1, word2, 'VariableNames', {'v1', 'v2', 'word1', 'word2'})
tNew = 3×4 table
v1 v2 word1 word2 _______ _______ _______ _________ 0.58296 0.34595 {'abc'} {'def' } 0.68275 0.43401 {'ghi'} {'jklmn'} 0.96797 0.68611 {'xyz'} {'123' }
  1 个评论
Siddharth Bhutiya
If the char data is always split into two separate words then another way to do this (without using for loops) would be to first use split to split the Nx1 cellstr into a Nx2 cellstr and then use splitvars to split the 2 column cellstr variable into two separate variables
t = table(v1, str, v2)
t =
3×3 table
v1 str v2
_______ _____________ _______
0.81472 {'abc def' } 0.91338
0.90579 {'ghi jklmn'} 0.63236
0.12699 {'xyz 123' } 0.09754
t.str = split(t.str)
t =
3×3 table
v1 str v2
_______ ____________________ _______
0.81472 {'abc'} {'def' } 0.91338
0.90579 {'ghi'} {'jklmn'} 0.63236
0.12699 {'xyz'} {'123' } 0.09754
t = splitvars(t,"str","NewVariableNames",["Word1" "Word2"])
t =
3×4 table
v1 Word1 Word2 v2
_______ _______ _________ _______
0.81472 {'abc'} {'def' } 0.91338
0.90579 {'ghi'} {'jklmn'} 0.63236
0.12699 {'xyz'} {'123' } 0.09754

请先登录,再进行评论。

更多回答(1 个)

Voss
Voss 2021-12-26
Maybe you can use strsplit.

类别

Help CenterFile Exchange 中查找有关 Tables 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by