00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025 #ifndef EIGEN_LEASTSQUARES_H
00026 #define EIGEN_LEASTSQUARES_H
00027
00100 template<typename VectorType>
00101 void linearRegression(int numPoints,
00102 VectorType **points,
00103 VectorType *result,
00104 int funcOfOthers )
00105 {
00106 typedef typename VectorType::Scalar Scalar;
00107 typedef Hyperplane<Scalar, VectorType::SizeAtCompileTime> HyperplaneType;
00108 const int size = points[0]->size();
00109 result->resize(size);
00110 HyperplaneType h(size);
00111 fitHyperplane(numPoints, points, &h);
00112 for(int i = 0; i < funcOfOthers; i++)
00113 result->coeffRef(i) = - h.coeffs()[i] / h.coeffs()[funcOfOthers];
00114 for(int i = funcOfOthers; i < size; i++)
00115 result->coeffRef(i) = - h.coeffs()[i+1] / h.coeffs()[funcOfOthers];
00116 }
00117
00145 template<typename VectorType, typename HyperplaneType>
00146 void fitHyperplane(int numPoints,
00147 VectorType **points,
00148 HyperplaneType *result,
00149 typename NumTraits<typename VectorType::Scalar>::Real* soundness = 0)
00150 {
00151 typedef typename VectorType::Scalar Scalar;
00152 typedef Matrix<Scalar,VectorType::SizeAtCompileTime,VectorType::SizeAtCompileTime> CovMatrixType;
00153 EIGEN_STATIC_ASSERT_VECTOR_ONLY(VectorType)
00154 ei_assert(numPoints >= 1);
00155 int size = points[0]->size();
00156 ei_assert(size+1 == result->coeffs().size());
00157
00158
00159 VectorType mean = VectorType::Zero(size);
00160 for(int i = 0; i < numPoints; ++i)
00161 mean += *(points[i]);
00162 mean /= numPoints;
00163
00164
00165 CovMatrixType covMat = CovMatrixType::Zero(size, size);
00166 VectorType remean = VectorType::Zero(size);
00167 for(int i = 0; i < numPoints; ++i)
00168 {
00169 VectorType diff = (*(points[i]) - mean).conjugate();
00170 covMat += diff * diff.adjoint();
00171 }
00172
00173
00174 SelfAdjointEigenSolver<CovMatrixType> eig(covMat);
00175 result->normal() = eig.eigenvectors().col(0);
00176 if (soundness)
00177 *soundness = eig.eigenvalues().coeff(0)/eig.eigenvalues().coeff(1);
00178
00179
00180
00181 result->offset() = - (result->normal().cwise()* mean).sum();
00182 }
00183
00184
00185 #endif // EIGEN_LEASTSQUARES_H