Moving Averages SMA !

Hello,

I am trying to create a awk script to calculate the simple moving average of two fields but I got only the result of the first field.

Could you please help me to fix this awk shell script

awk -F, -v points=5 '

 { 
 a[NR % points] = $2;
 b[NR % points] = $3;
 if(NR>=points) {
 total_a = 0;
 total_b = 0;
 for (i = 0; i < points; ++i) 
     { total_a = total_a + a; }
     { total_b = total_b + b; }
 print ($1, $2, total_a/points, $3, total_b/points);
 }
 }' data.test


"data.test"
001,10,100
002,11,110
003,12,111
004,13,111
005,14,110
006,14,110
007,15,109
008,14,108
009,13,107
010,13,108

output expected

Row     Field2  MA      Field3  MA
5    14    12    110    108.4
6    14    12.8    110    110.4
7    15    13.6    109    110.2
8    14    14    108    109.6
9    13    14    107    108.8
10    13    13.8    108    108.4

awk -F, -v points=5 '

 { 
 a[NR % points] = $2;
 b[NR % points] = $3;
 if(NR>=points) {
 total_a = 0;
 total_b = 0;
 for (i = 0; i < points; ++i) 
     { total_a = total_a + a; 
      total_b = total_b + b; }
 print ($1, $2, total_a/points, $3, total_b/points);
 }
 }' data.test
1 Like