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

7 views (last 30 days)
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...

Accepted Answer

sudobash
sudobash on 11 Aug 2022
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.

More Answers (1)

Abderrahim. B
Abderrahim. B on 11 Aug 2022
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

Categories

Find more on Time Series 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!