Friday, September 12, 2008

Matrix addition using awk in bash


This is how can do matrix addition using awk ( basically adding columns of two files)

Input files:

$ cat mat1.txt
1 5 6
2 2 6
4 1 8

$ cat mat2.txt
4 5 3
2 4 5
2 4 6

Output required:
5 10 9
4 6 11
6 5 14

$ awk '
FNR==NR {
for(i=1; i<=NF; i++)
_[FNR,i]=$i
next
}
{
for(i=1; i<=NF; i++)
printf("%d%s", $i+_[FNR,i], (i==NF) ? "\n" : FS);
}' mat1.txt mat2.txt

No comments:

© Jadu Saikia www.UNIXCL.com