MATLAB: Reshape table by rows, then merge horizontally and new var names

databasereshapesubmatrixtable

Hi
I have a long table dataset with 6 columns (DAY YEAR serial var1 var2 var3). Column DAY repeated values [1, 2, 3, …,365, 1, …,365,….]. Column YEAR has the same value for every 365 rows [2010 repeat365 times, 2011 repeat 365 times,….].
I want it to be divided into every 365 rows (have the same value in column B), merge the new subsets horizontally. Another problem is the reshaped new wide-table will have repeatedly variables names, how can I reshape the table and rename variables to (DAY var1_2010 var2_2010 var4_2010 var1_2011 var2_2011 var3_2011 var1_2012…)? Thank you.

Best Answer

Unstack:
>> t = table([1;1;1;2;2;2;3;3;3;4;4;4],[1;2;3;1;2;3;1;2;3;1;2;3],[1;2;3;4;5;6;7;8;9;10;11;12])
t =
12×3 table
Var1 Var2 Var3
____ ____ ____
1 1 1
1 2 2
1 3 3
2 1 4
2 2 5
2 3 6
3 1 7
3 2 8
3 3 9
4 1 10
4 2 11
4 3 12
>> unstack(t,'Var3','Var2','GroupingVariable','Var1')
Warning: Table variable names were modified to make them valid MATLAB identifiers.
ans =
4×4 table
Var1 x1 x2 x3
____ __ __ __
1 1 2 3
2 4 5 6
3 7 8 9
4 10 11 12