Reputation: 41
I'm trying to find a function in MatLab that is similar to the 'melt' function in the R package "reshape2", such that the row headers are repeated for each variable and stacked together.
e.g.:
If I have a matrix
A 1 2 3
B 4 5 6
C 7 8 9
I'd like to change it to
A 1
A 2
A 3
B 4
B 5
B 6
C 7
C 8
C 9
Short of working a for() loop to go pair-wise through each column, is there a function that could do this?
Many thanks, KRB
Upvotes: 3
Views: 1301
Reputation: 15718
Matlab has stack
and unstack
functions, operating on tables, which are similar to melt
and cast
. Something like this would work
groups = {'A'; 'B'; 'C'};
A1 = [1; 4; 7];
A2 = [2; 5; 8];
A3 = [3 ; 6; 9];
T = table(groups, A1, A2, A3)
TLong = stack(T, 2:4)
which gives
TLong =
groups A1_A2_A3_Indicator A1_A2_A3
______ __________________ ________
'A' A1 1
'A' A2 2
'A' A3 3
'B' A1 4
'B' A2 5
'B' A3 6
'C' A1 7
'C' A2 8
'C' A3 9
Note that your example matrix cannot exist in Matlab (or R) as matrices cannot contain strings or mixed types. I recommend you convert whatever structure you have now to a table
if you want to use a inbuilt function.
Upvotes: 2