How to split a column with a numeric data into multiple columns by digits in timetable?

3 次查看(过去 30 天)
Hello, Thank you for helping this out.
I have a timetable (345533X1 timetable) like below with a numeric numbers in Var1:
Time Var1
20220804 00:00:01 1577990
20220804 00:00:02 1576990
... ...
What I want to get is timetable with seperated columns (345533X7 timetable):
Time Var1 Var2 Var3 Var4 Var5 Var6 Var7
20220804 00:00:01 1 5 7 7 9 9 0
20220804 00:00:02 1 5 7 6 9 9 0
... ... ... .... ... ... ... ....
Do you have an idea to solve this out..?
I tried split functions, but it won't go well...

采纳的回答

sudobash
sudobash 2022-8-11
Hello!
As per my understanding, each digit of the column needs to be split into separate columns. I've taken the assumption that the length of each number is the same. Here is my solution:
% Creating example input table
inputTable = table();
inputTable.Time = ["20220804 00:00:01"; "20220804 00:00:02"];
inputTable.Var = [1577990; 1576990];
inputTable = 2×2 table
Time Var ___________________ _________ "20220804 00:00:01" 1.578e+06 "20220804 00:00:02" 1.577e+06
% Solution
numCols = strlength(string(inputTable.Var(1)));
colNames = [];
for i=numCols:-1:1
colName = "Var" + string(i);
colNames = [colNames colName];
t = mod(inputTable.Var,10); % Extract each digit from the number
inputTable.Var = floor(inputTable.Var / 10);
inputTable.(colName) = t;
end
inputTable = removevars(inputTable,"Var"); % Delete the initial input column
inputTable
inputTable = 2×8 table
Time Var7 Var6 Var5 Var4 Var3 Var2 Var1 ___________________ ____ ____ ____ ____ ____ ____ ____ "20220804 00:00:01" 0 9 9 7 7 5 1 "20220804 00:00:02" 0 9 9 6 7 5 1
The columns are in reverse order. This can be solved by using the movevars method. For more information on movevars refer this link.
Hope this solves your question.

更多回答(1 个)

Abderrahim. B
Abderrahim. B 2022-8-11
Hi!
Below will not work for negative elements ...
Time = datetime(["20220804T000001"; "20220804T000002"],'InputFormat','uuuuMMdd''T''HHmmss') ;
nbr = [12455; 12456] ;
var = str2double(string(num2str(nbr) - '0')) ;
tbl = table2timetable(addvars( array2table(var), Time, 'Before', 'var1'))
tbl = 2×5 timetable
Time var1 var2 var3 var4 var5 ____________________ ____ ____ ____ ____ ____ 04-Aug-2022 00:00:01 1 2 4 5 5 04-Aug-2022 00:00:02 1 2 4 5 6
Hope this helps

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by