001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.math4.legacy.stat.descriptive.moment; 018 019import java.util.Arrays; 020 021import org.apache.commons.math4.legacy.exception.DimensionMismatchException; 022 023/** 024 * Returns the arithmetic mean of the available vectors. 025 * @since 1.2 026 */ 027public class VectorialMean { 028 /** Means for each component. */ 029 private final Mean[] means; 030 031 /** Constructs a VectorialMean. 032 * @param dimension vectors dimension 033 */ 034 public VectorialMean(int dimension) { 035 means = new Mean[dimension]; 036 for (int i = 0; i < dimension; ++i) { 037 means[i] = new Mean(); 038 } 039 } 040 041 /** 042 * Add a new vector to the sample. 043 * @param v vector to add 044 * @throws DimensionMismatchException if the vector does not have the right dimension 045 */ 046 public void increment(double[] v) throws DimensionMismatchException { 047 if (v.length != means.length) { 048 throw new DimensionMismatchException(v.length, means.length); 049 } 050 for (int i = 0; i < v.length; ++i) { 051 means[i].increment(v[i]); 052 } 053 } 054 055 /** 056 * Get the mean vector. 057 * @return mean vector 058 */ 059 public double[] getResult() { 060 double[] result = new double[means.length]; 061 for (int i = 0; i < result.length; ++i) { 062 result[i] = means[i].getResult(); 063 } 064 return result; 065 } 066 067 /** 068 * Get the number of vectors in the sample. 069 * @return number of vectors in the sample 070 */ 071 public long getN() { 072 return (means.length == 0) ? 0 : means[0].getN(); 073 } 074 075 /** {@inheritDoc} */ 076 @Override 077 public int hashCode() { 078 final int prime = 31; 079 int result = 1; 080 result = prime * result + Arrays.hashCode(means); 081 return result; 082 } 083 084 /** {@inheritDoc} */ 085 @Override 086 public boolean equals(Object obj) { 087 if (this == obj) { 088 return true; 089 } 090 if (!(obj instanceof VectorialMean)) { 091 return false; 092 } 093 VectorialMean other = (VectorialMean) obj; 094 return Arrays.equals(means, other.means); 095 } 096}