seperating char data at matlab
1 view (last 30 days)
Show older comments
Cem Eren Aslan
on 26 Dec 2021
Commented: Siddharth Bhutiya
on 3 Jan 2022
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
0 Comments
Accepted Answer
Image Analyst
on 26 Dec 2021
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)
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'})
1 Comment
Siddharth Bhutiya
on 3 Jan 2022
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
More Answers (1)
See Also
Categories
Find more on Cell Arrays 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!