I have a gridded data file in column format as:
ifile.txt
x y value
20.5 20.5 -4.1
21.5 20.5 -6.2
22.5 20.5 0.0
20.5 21.5 1.2
21.5 21.5 4.3
22.5 21.5 6.0
20.5 22.5 7.0
21.5 22.5 10.4
22.5 22.5 16.7
I would like to convert it to matrix format as:
ofile.txt
20.5 21.5 22.5
20.5 -4.1 1.2 7.0
21.5 -6.2 4.3 10.4
22.5 0.0 6.0 16.7
Where top 20.5 21.5 22.5
indicate y and side values indicate x and the inside values indicate the corresponding grid values.
I found a similar question here Convert a 3 column file to matrix format but the script is not working in my case.
The script is
awk '{ h[$1,$2] = h[$2,$1] = $3 }
END {
for(i=1; i<=$1; i++) {
for(j=1; j<=$2; j++)
printf h[i,j] OFS
printf "\n"
}
}' ifile
Adjusted my old GNU
awk
solution for your current input data:matrixize.awk
script:Usage:
The output:
Perl solution:
-n
reads the input line by line-a
splits each line on whitespace into the @F arrayawk
solution:Explanations:
sort -n ifile.txt
sort the file numericallyheader="\t"
and will be appended with the necessary information thanks toheader=header sprintf("%4.1f\t",$1)
for lines respecting(NR-1)%3==1)
matrix
variable:matrix=matrix sprintf("%4.1f\t",$1)
will create the first column andmatrix= matrix sprintf("%4.1f\t",$3)
will populate the matrix with the content thenif((NR-1)%3==0 && NR!=10)matrix=matrix "\n"
will add the adequate EOLThe following
awk
script handles :This is done in this way:
How does it work:
PROCINFO["sorted_in"] = "@ind_num_asc"
, states that all arrays are sorted numerically by index.(NR==1){next}
: skip the first line{row[$1]=1;col[$2]=1;val[$1" "$2]=$3}
, process the line by storing the row and column index and accompanying value.This outputs:
note: the usage of
PROCINFO
is agawk
feature.However, if you make a couple of assumptions, you can do it much shorter:
The you can use the following short versions:
which outputs
or for the transposed:
This outputs