public static double[][] centerAndScale(double[][] matrix){
  final double[][] result=matrix.clone();
  final int nRows=result.length;
  final int nCols=result[0].length;
  if (nRows < 2 || nCols == 0)   return result;
  for (int col=0; col < nCols; col++) {
    double mean=0;
    for (    double[] aRow : result) {
      mean+=aRow[col];
    }
    mean/=nRows;
    for (    double[] aRow : result) {
      aRow[col]-=mean;
    }
  }
  for (int col=0; col < nCols; col++) {
    double sumOfSquares=0;
    for (    double[] aRow : result) {
      sumOfSquares+=aRow[col] * aRow[col];
    }
    double value=Math.sqrt(sumOfSquares / (nRows - 1));
    if (value != 0) {
      for (      double[] aRow : result) {
        aRow[col]/=value;
      }
    }
  }
  return result;
}

public static double [ ] [ ] centerAndScale ( double [ ] [ ] matrix ) { final double [ ] [ ] result = matrix . clone ( ) ; final int nRows = result . length ; final int nCols = result [ 0 ] . length ; if ( nRows < 2 || nCols == 0 ) return result ; for ( int col = 0 ; col < nCols ; col ++ ) { double mean = 0 ; for ( double [ ] aRow : result ) { mean += aRow [ col ] ; } mean /= nRows ; for ( double [ ] aRow : result ) { aRow [ col ] -= mean ; } } for ( int col = 0 ; col < nCols ; col ++ ) { double sumOfSquares = 0 ; for ( double [ ] aRow : result ) { sumOfSquares += aRow [ col ] * aRow [ col ] ; } double value = Math . sqrt ( sumOfSquares / ( nRows - 1 ) ) ; if ( value != 0 ) { for ( double [ ] aRow : result ) { aRow [ col ] /= value ; } } } return result ; }
center and scale a given matrix . center means : subtract column - mean from each column scale means : divide each column by square root of ( sum - of - squares of column / ( number of columns - 1 ) ) see http : / / docs . tibco . com / pub / enterprise - runtime - for - r / 1 . 1 . 0 - november - 2012 / terr_1 . 1 . 0_languageref / base / scale . html
