View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.math.stat.descriptive.moment;
18  
19  import java.io.Serializable;
20  
21  import org.apache.commons.math.DimensionMismatchException;
22  
23  /**
24   * Returns the arithmetic mean of the available vectors.
25   * @since 1.2
26   * @version $Revision: 619928 $ $Date: 2008-02-08 09:19:17 -0700 (Fri, 08 Feb 2008) $
27   */
28  public class VectorialMean implements Serializable {
29  
30      /** Serializable version identifier */
31      private static final long serialVersionUID = 8223009086481006892L;
32  
33      /** Means for each component. */
34      private Mean[] means;
35  
36      /** Constructs a VectorialMean.
37       * @param dimension vectors dimension
38       */
39      public VectorialMean(int dimension) {
40          means = new Mean[dimension];
41          for (int i = 0; i < dimension; ++i) {
42              means[i] = new Mean();
43          }
44      }
45  
46      /**
47       * Add a new vector to the sample.
48       * @param v vector to add
49       * @exception DimensionMismatchException if the vector does not have the right dimension
50       */
51      public void increment(double[] v) throws DimensionMismatchException {
52          if (v.length != means.length) {
53              throw new DimensionMismatchException(v.length, means.length);
54          }
55          for (int i = 0; i < v.length; ++i) {
56              means[i].increment(v[i]);
57          }
58      }
59  
60      /**
61       * Get the mean vector.
62       * @return mean vector
63       */
64      public double[] getResult() {
65          double[] result = new double[means.length];
66          for (int i = 0; i < result.length; ++i) {
67              result[i] = means[i].getResult();
68          }
69          return result;
70      }
71  
72      /**
73       * Get the number of vectors in the sample.
74       * @return number of vectors in the sample
75       */
76      public long getN() {
77          return (means.length == 0) ? 0 : means[0].getN();
78      }
79  
80  }