简体   繁体   中英

Is there a similar function to 'melt' in reshape2 in R that works in MatLab?

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.

eg:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM