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

1 comment:

Unknown said...


cat matrix1 |
dc -e "
$(cat matrix2.txt)
[q]sq
[SA]sa
[z 0 <a z 0 <b]sb
[SB z 0 <c]sc
[[]p]se
[LBLA+n [ ]n lK1-0=e lK1-dsK 0 <d]sd
[? z 0 =q zsK lcx ldx c l?x]s?
lbx l?x
"

© Jadu Saikia www.UNIXCL.com