Transform columns to matrix

The following code transform the matrix to columns. Is it possible to do it other way around ( get the input from the output) ?

input

    y1  y2  y3  y4  y5
x1 0.3 0.5 2.3 3.1 5.1
x2 1.2 4.1 3.5 1.7 1.2
x3 3.1 2.1 1.0 4.1 2.1
x4 5.0 4.0 6.0 7.0 1.1

output

x1 y1 0.3 
x2 y1 1.2 
x3 y1 3.1 
x4 y1 5.0 
x1 y2 0.5
x2 y2 4.1
x3 y2 2.1
x4 y2 4.0
x1 y3 2.3 
x2 y3 3.5
x3 y3 1.0
x4 y3 6.0
x1 y4 3.1
x2 y4 1.7 
x3 y4 4.1 
x4 y4 7.0
x1 y5 5.1
x2 y5 1.2 
x3 y5 2.1 
x4 y5 1.1

script (matrix to columns)

awk 'NR==1{n=split($0,c);next}
{for(i=1;i<=n;i++)s[++t]=$1 FS c FS $(i+1)}
END{for(i=1;i<=t;i++){print s}}
' file | sort -k2,2

Try

awk     '       {LN[$1]; HD[$2]; MX[$1,$2]=$3}
         END    {               printf "%10s", ""; for (i in HD) printf "%10s", i; print "";
                 for (j in LN) {printf "%10s",j;   for (i in HD) printf "%10s", MX[j,i]; print ""}
                }
        ' file
                  y1        y2        y3        y4        y5
        x1       0.3       0.5       2.3       3.1       5.1
        x2       1.2       4.1       3.5       1.7       1.2
        x3       3.1       2.1       1.0       4.1       2.1
        x4       5.0       4.0       6.0       7.0       1.1
1 Like