seperating char data at matlab

1 visualización (últimos 30 días)
Cem Eren Aslan
Cem Eren Aslan el 26 de Dic. de 2021
Comentada: Siddharth Bhutiya el 3 de En. de 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

Respuesta aceptada

Image Analyst
Image Analyst el 26 de Dic. de 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)
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 comentario
Siddharth Bhutiya
Siddharth Bhutiya el 3 de En. de 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

Iniciar sesión para comentar.

Más respuestas (1)

Voss
Voss el 26 de Dic. de 2021
Maybe you can use strsplit.

Categorías

Más información sobre Cell Arrays en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by