Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate deviation equation using awk

Tags:

shell

awk

I have a math equation in which I have to use the first column of a file to calculate a mean absolute deviation and I am stuck trying to use awk to calculate it

this is the equation:

In which α corresponds to the values of the first column of the test.2 file(shown below), and n is the number of lines the file has (excluding the first one).

the file would look something like this

 79
  1    4.4278   2.2139   2.1869   3.0000   0.0000   0.0000   0.0000
  2    6.9588   3.4794   2.9968   5.0000   0.0000   0.0000   0.0000
  3    6.5200   3.7258   2.8564   2.0000   1.0000   0.0000   0.0000
  4    6.4927   3.7101   2.8477   2.5000   1.0000   0.0000   0.0000
  5    6.2338   3.5621   2.7648   2.5000   1.0000   0.0000   0.0000
  6    6.1514   3.5150   2.7384   2.5000   1.0000   0.0000   0.0000
  7    6.5048   3.7171   2.8515   2.5000   1.0000   0.0000   0.0000
  8    6.6012   3.7722   2.8824   2.5000   1.0000   0.0000   0.0000

With values going until it reaches 79 lines. The first value is the number of lines n which I am trying to get using

n = awk ‘NR == 1 {print $1}’ test.2

but I have no idea how to calculate all the α from the test.2 file and then calculate the sum.

The only thing I tested this far is

for i in $(seq 1 "${n}"); do
        i=$((i+1))
        a=awk 'NR == $i {print $2}' test.2
        x=$(awk -F'[-,]' '({print sqrt((a[{$i}]-2a[${i}+1]+a[${i}+2])ˆ2)}')
        stdev=$x/(n-2)
done

echo "$stdev"
like image 262
Miro Feliciano Avatar asked Dec 05 '25 18:12

Miro Feliciano


1 Answers

It should be roughly like this, but you need to test and correct.

awk '                                    
NR == 1 { n = $1 }                       
NR > 1 {                                 
 a[0] = a[1];                            
 a[1] = a[2];                            
 a[2] = $2;                              
 if (NR > 3) {                           
   row_value = ( a[0] - 2 * a[1] + a[2] )
   if (row_value < 0) {                  
     row_value = - row_value             
   }                                     
   sum += row_value                      
 }                                       
}                                        
END { print sum / (n - 2) }' test.2
like image 144
perreal Avatar answered Dec 08 '25 07:12

perreal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!