/* matutil.c

   written by Don Robert Maszle
   18 September 1992
   
   Copyright (c) 1993.  Don Maszle, Frederic Bois.  All rights reserved.

   -- Revisions -----
     Logfile:  SCCS/s.matutil.c
    Revision:  1.1
        Date:  7/14/93
     Modtime:  19:14:45
      Author:  @a
   -- SCCS  ---------

   A bunch of matrix and vector utililties.
*/


#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include "sim.h"

/* LogTransformArray

   log-transforms the elements of a Src array to a Destination array,
   which is returned. 

   To transform in place, give the same pointer for both args.
*/

double *LogTransformArray (long nElems, double *rgdSrc, double *rgdDes)
{
  register long l;

  for (l = 0; l < nElems; l++)
    rgdDes[l] = log(rgdSrc[l]);

  return rgdDes;
}  /* LogTransformArray */


/* InitVectorsVector

   initializes a vectors of vectors of double.

   If rgp is non-NULL, the initial vector is assumes to exist, and each
   of the cVectors elements is initialized to a vector of cElemsEach of
   double.

   If rgp is NULL, the vectors of pointers to the secondary vectors is
   allocated and then initialized as described.

   In both cases, the pointer to the vector of vectors is returned if no
   error occurs, otherwise NULL is returned.
*/

double **InitVectorsVector (double **rgpIn, long cVectors, long cElemsEach)
{
  long i;
  double **rgp = rgpIn;

  if (!rgp)
    rgp = NewVector (double *, cVectors);

  if (rgp) {
    for (i = 0; i < cVectors; i++) {
      rgp[i] = NewVector (double, cElemsEach);
      if (!rgp[i]) {
	rgp = 0;
	break;
      }  /* if */
    }  /* for */
  }  /* if */

  if (!rgp) {
    fprintf (stderr, "*** Out of memory: InitVectorsVector\n");
    exit (-1);
  }  /* if */

  return (rgp);
}  /* **InitVectorsVector */


void ColumnMeans (long cRows, long cCols, double **x, double *x_bar)
{
  register long i, l;
  
  for (l = 0; l < cCols; l++)
    x_bar[l] = 0.0;
  for (i = 0; i < cRows; i++)
    for (l = 0; l < cCols; l++)
      x_bar[l] += x[i][l];
  for (l = 0; l < cCols; l++)
    x_bar[l] /= cRows;
      
}  /* ColumnMean */
      

