' ******************************************************************
' One-way analysis of variance
' ******************************************************************

#INCLUDE "fbmath.bi"

#DEFINE Nsamples 5
#DEFINE Nmax     12
#DEFINE Alpha    0.05

' Sample matrix (one sample per column)
DIM AS DOUBLE A(1 TO Nmax, 1 TO Nsamples) = _
{{7.2,  4.9, 10.4,  4.6,  6.1}, _
 {4.3,  4.8,  4.6,  5.6, 11.4}, _
 {5.5,  4.7,  8.4,  8.3,  8.2}, _
 {4.6,  5.4,  6.1,  6.9,  5.7}, _
 {4.7,  4.7,  8.1,  4.5,  6.6}, _
 {5.5,  4.7,  5.4,  4.7,  6.6}, _
 {6.6,  6.2,  6.7,  6.7,  6.3}, _
 {5.3,  5.6,  7.5,  4.8,  5.9}, _
 {5.4,  3.2,  6.4,  5.0,  5.8}, _
 {3.9,  6.1,  5.6,  5.0,  4.8}, _
 {5.5,  6.7,  6.3,  5.3,  9.1}, _
 {2.7,  5.5,  7.7,  7.8, 13.2}}

DIM AS DOUBLE  X(1 TO Nmax)       ' Sample
DIM AS INTEGER N(1 TO Nsamples)   ' Sizes
DIM AS DOUBLE  M(1 TO Nsamples)   ' Means
DIM AS DOUBLE  S(1 TO Nsamples)   ' Standard dev.

DIM AS DOUBLE  V_f, V_r, F        ' Variances and variance ratio
DIM AS DOUBLE  Khi2               ' Bartlett's khi-2
DIM AS DOUBLE  H                  ' Kruskal-Wallis H
DIM AS DOUBLE  P                  ' Probability
DIM AS DOUBLE  Fc, K2c            ' Critical values
DIM AS INTEGER DoF_f, DoF_r, DoF  ' Degrees of freedom
DIM AS INTEGER J                  ' Loop variable

SUB GetSample(A() AS DOUBLE, J AS INTEGER, X() AS DOUBLE)
' Get sample J from matrix A into vector X

  DIM I AS INTEGER

  FOR I = 1 TO Nmax
    X(I) = A(I, J)
  NEXT I
END SUB

' Compute sizes, means and SD's
FOR J = 1 TO Nsamples
  GetSample A(), J, X()
  N(J) = Nmax
  M(J) = Mean(X())
  S(J) = StDev(X(), M(J))
NEXT J

' Compare means and variances (parametric tests)
AnOVa1 N(), M(), S(), V_f, V_r, F, DoF_f, DoF_r
Bartlett N(), S(), Khi2, DoF

' Compare means (non-parametric test)
Kruskal_Wallis N(), A(), H, DoF

' Compute critical values
P = 1 - Alpha
Fc = InvSnedecor(DoF_f, DoF_r, P)
K2c = InvKhi2(DoF, P)

PRINT "Sample     Mean       St.Dev."
PRINT "-----------------------------"

FOR J = 1 TO Nsamples
  PRINT USING "######  ####.####  ####.####"; J; M(J); S(J)
NEXT J

PRINT

PRINT "Comparison of means (One-way analysis of variance):"
PRINT
PRINT USING "Factorial variance         = ####.####  (### DoF)"; V_f; DoF_f
PRINT USING "Residual variance          = ####.####  (### DoF)"; V_r; DoF_r
PRINT USING "Variance ratio             = ####.####"; F
PRINT USING "Critical value (p = #.###) = ####.####"; Alpha; Fc

PRINT

PRINT "Comparison of variances:"
PRINT
PRINT USING "Bartlett's Khi-2           = ####.####  (### DoF)"; Khi2; DoF
PRINT USING "Critical value (p = #.###) = ####.####"; Alpha; K2c
PRINT

PRINT "Comparison of means (Non-parametric test):"
PRINT
PRINT USING "Kruskal-Wallis H           = ####.####  (### DoF)"; H; DoF
PRINT USING "Critical value (p = #.###) = ####.####"; Alpha; K2c

SLEEP
