Lower triangular matrix

Hi,
I was wondering if there is a way of using awk to extract the lower or upper triangular matrix from a symmetric matrix. Say I have this matrix:
$ cat data:

1 0 9 6 7 9
0 8 2 8 9 0
9 2 6 9 4 3
6 8 9 6 9 4
7 9 4 9 9 7
9 0 3 4 7 9

I am trying to do two things.
Result 1:

0 9 2 6 8 9 7 9 4 9 9 0 3 4 7 

Result 2:

1 0 8 9 2 6 6 8 9 6 7 9 4 9 9 9 0 3 4 7 9

Result 1 has only the lower triangular without the diagonal while result 2 has the lower triangular and the diagonal.

Thanks.

$ awk '{for (i=1;i<=NF;i++) if (i<=NR) printf $i FS}' infile
1 0 8 9 2 6 6 8 9 6 7 9 4 9 9 9 0 3 4 7 9

$ awk '{for (i=1;i<=NF;i++) if (i<NR) printf $i FS}' infile
0 9 2 6 8 9 7 9 4 9 9 0 3 4 7
2 Likes

Thanks, it worked

---------- Post updated 12-11-12 at 10:57 AM ---------- Previous update was 12-10-12 at 08:52 PM ----------

Can these be done to appear in one column instead of one row? The matrix I have is a very large one.
Thanks

Replace FS with RS.

1 Like

A bit shorter:

$ awk '{i=0;while (++i<=NR) printf $i FS}' file
1 0 8 9 2 6 6 8 9 6 7 9 4 9 9 9 0 3 4 7 9

$ awk '{i=0;while (++i<NR) printf $i FS}' file
0 9 2 6 8 9 7 9 4 9 9 0 3 4 7