Saturday, October 1, 2011

AWK-Part 2: Matrix Manipulation

1. Transpose

more input.txt
2.3 3.2 3.6
4.2 1.3 6.5
5.1 4.2 9.3

more output.txt
2.3 4.2 5.1
3.2 1.3 4.2
3.6 6.5 9.3

awk '{
for (f = 1; f <= NF; f++)
a[NR, f] = $f
}
NF > nf { nf = NF }
END {
for (f = 1; f <= nf; f++)
for (r = 1; r <= NR; r++)
printf a[r, f] (r==NR ? RS : FS)
}' input.txt > output.txt


Jika dengan Bourne Shell, copy kode berikut lalu berinama transpose,
Jalankan dengan perintah sh transpose input.txt > output.txt

#! /bin/sh
exec awk '
NR == 1 {
n = NF
for (i = 1; i <= NF; i++)
row[i] = $i
next
}
{
if (NF > n)
n = NF
for (i = 1; i <= NF; i++)
row[i] = row[i] " " $i
}
END {
for (i = 1; i <= n; i++)
print row[i]
}' ${1+"$@"}



2. Mengurangi Matrix dengan bilangan (0.4)
awk '{for(i=1;i <=NF;++i)$i-=0.4;print}' input.txt > output.txt

more input.txt
2.3 3.2 3.6
4.2 1.3 6.5
5.1 4.2 9.3

more output.txt
1.9 2.8 3.2
3.8 0.9 6.1
4.7 3.8 8.9


3. Menambahkan Matrix dengan bilangan (0.8)
awk '{for(i=1;i <=NF;++i)$i+=0.8;print}' input.txt > output.txt

more output.txt
3.1 4 4.4
5 2.1 7.3
5.9 5 10.1

4. Mengkalikan matrix dengan bilangan (10)
awk '{for(i=1;i <=NF;++i)$i*=10;print}' input.txt > output.txt

Untuk membagi dengan angka 10:
awk '{for(i=1;i <=NF;++i)$i/=10;print}' input.txt > output.txt


5. Pengurangan antara dua matrix
output.txt=matrix2-matrix1

more matrix1
3 3 3
3 3 3
3 3 3

more matrix2
1 1 1
1 1 1
1 1 1

awk '{n1=split($0,m1);getline <"matrix1";for(i=1;i <n1;++i)printf "%d ",m1[i]-$i;printf "%d\n",m1[n1]-$(n1)}' matrix2 > output.txt

more output.txt
-2 -2 -2
-2 -2 -2
-2 -2 -2

Modified from www.tek-tips.com

6. Menjumlahkan dua matrix
awk '{n1=split($0,m1);getline <"matrix1";for(i=1;i <n1;++i)printf "%d ",m1[i]+$i;printf "%d\n",m1[n1]+$(n1)}' matrix2


7. Sorting Matrix: ascending, dengan kolom ke 3 sebagai acuan

sort -k 3n < input.txt > output.txt

more input.txt
2.3 3.2 3.6
4.2 1.3 6.5
5.1 4.2 9.3
4.8 6.4 1.2
6.1 2.4 5.3
8.8 8.4 6.1
8.1 0.6 8.7

more output.txt
4.8 6.4 1.2
2.3 3.2 3.6
6.1 2.4 5.3
8.8 8.4 6.1
4.2 1.3 6.5
8.1 0.6 8.7
5.1 4.2 9.3

8. Sorting Matrix: descending, dengan kolom ke 3 sebagai acuan
sort -k 3nr < input.txt > output.txt

more output.txt
5.1 4.2 9.3
8.1 0.6 8.7
4.2 1.3 6.5
8.8 8.4 6.1
6.1 2.4 5.3
2.3 3.2 3.6
4.8 6.4 1.2

9. Membuat matrix dari 0 s/d 100 dengan penambahan 10

awk 'BEGIN {a=0;b=10; while(a <=100){print a;a=a+b}}' > numbers.txt

Dengan perintah seq
seq 0 10 100 > numbers.txt

more numbers.txt
0
10
20
30
40
50
60
70
80
90
100


10. Print input beberapa kali (contoh 3 kali):

more input.txt
2.3 3.2 3.6
4.2 1.3 6.5
5.1 4.2 9.3

more output.txt
2.3 3.2 3.6
4.2 1.3 6.5
5.1 4.2 9.3
2.3 3.2 3.6
4.2 1.3 6.5
5.1 4.2 9.3
2.3 3.2 3.6
4.2 1.3 6.5
5.1 4.2 9.3

#!/bin/sh
n=1
while [ $n -le 3 ]
do
awk '{print $0}' input.txt > > output.txt
n=$((n+1))
done

No comments: