seperating char data at matlab

조회 수: 1 (최근 30일)
Cem Eren Aslan
Cem Eren Aslan 2021년 12월 26일
댓글: Siddharth Bhutiya 2022년 1월 3일
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
Siddharth Bhutiya 2022년 1월 3일
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에서 Cell Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by