#! /bin/gawk -f # Last edited on 2005-10-28 13:46:44 by stolfi # Reads a sparse matrix (".mat" file). # Writes a PGM image showing the shape of the matrix. BEGIN { abort = -1; oldrow = -1; printf "P2\n"; } (abort >= 0){exit abort;} /rows *=/{ rows = $3; } /cols *=/ { cols = $3; printf "%d %d 255\n", rows, cols; split("", m); } /^[0-9]/{ row = $1 + 0; col = $2 + 0; if (row < oldrow) { error(("element out of order [" row "," col "]")); } if (oldrow < row) { if (oldrow >= 0) { printrow(); } oldrow++; split("", m); while (oldrow < row) { printrow(); oldrow++; } } if(col in m) { error(("repeated element [" row "," col "]")); } val = $3; if (val == "NaN") { m[col] = 0; } else if (val == 0) { m[col] = 255; } else { val = (val < 0 ? -val : val); mag = log(val)/log(10); if (mag < -20) { mag = -20; } if (mag > 20) { mag = 20; } m[col] = int(128 - 5*mag + 0.5); } } END { if(abort >= 0) { exit abort;} if (oldrow >= 0) { printrow(); } } function printrow( i) { for (i = 0; i < cols; i++) { printf " %d", (i in m ? m[i] : 255); } printf "\n"; } function error(msg) { printf "line %d: %s\n", FNR, msg > "/dev/stderr"; abort = 1; exit 1; }