mlpack
ccov_impl.hpp
Go to the documentation of this file.
1 
13 #ifndef MLPACK_CORE_MATH_CCOV_IMPL_HPP
14 #define MLPACK_CORE_MATH_CCOV_IMPL_HPP
15 
16 #include "ccov.hpp"
17 
18 namespace mlpack {
19 namespace math {
20 
21 template<typename eT>
22 inline arma::Mat<eT> ColumnCovariance(const arma::Mat<eT>& x,
23  const size_t normType)
24 {
25  if (normType > 1)
26  {
27  Log::Fatal << "ColumnCovariance(): norm_type must be 0 or 1!" << std::endl;
28  }
29 
30  arma::Mat<eT> out;
31 
32  if (x.n_elem > 0)
33  {
34  const arma::Mat<eT>& xAlias = (x.n_cols == 1) ?
35  arma::Mat<eT>(const_cast<eT*>(x.memptr()), x.n_cols, x.n_rows, false,
36  false) :
37  arma::Mat<eT>(const_cast<eT*>(x.memptr()), x.n_rows, x.n_cols, false,
38  false);
39 
40  const size_t n = xAlias.n_cols;
41  const eT normVal = (normType == 0) ? ((n > 1) ? eT(n - 1) : eT(1)) : eT(n);
42 
43  const arma::Mat<eT> tmp = xAlias.each_col() - arma::mean(xAlias, 1);
44 
45  out = tmp * tmp.t();
46  out /= normVal;
47  }
48 
49  return out;
50 }
51 
52 template<typename T>
53 inline arma::Mat<std::complex<T>> ColumnCovariance(
54  const arma::Mat<std::complex<T>>& x,
55  const size_t normType)
56 {
57  if (normType > 1)
58  {
59  Log::Fatal << "ColumnCovariance(): norm_type must be 0 or 1" << std::endl;
60  }
61 
62  typedef typename std::complex<T> eT;
63 
64  arma::Mat<eT> out;
65 
66  if (x.is_vec())
67  {
68  if (x.n_rows == 1)
69  {
70  const arma::Mat<T> tmpMat = arma::var(arma::trans(x), normType);
71  out.set_size(1, 1);
72  out[0] = tmpMat[0];
73  }
74  else
75  {
76  const arma::Mat<T> tmpMat = arma::var(x, normType);
77  out.set_size(1, 1);
78  out[0] = tmpMat[0];
79  }
80  }
81  else
82  {
83  const size_t n = x.n_cols;
84  const eT normVal = (normType == 0) ?
85  ((n > 1) ? eT(n - 1) : eT(1)) : eT(n);
86 
87  const arma::Col<eT> acc = arma::sum(x, 1);
88 
89  out = x * arma::trans(arma::conj(x));
90  out -= (acc * arma::trans(arma::conj(acc))) / eT(n);
91  out /= normVal;
92  }
93 
94  return out;
95 }
96 
97 } // namespace math
98 } // namespace mlpack
99 
100 #endif // MLPACK_CORE_MATH_CCOV_IMPL_HPP
static MLPACK_EXPORT util::PrefixedOutStream Fatal
Prints fatal messages prefixed with [FATAL], then terminates the program.
Definition: log.hpp:90
Linear algebra utility functions, generally performed on matrices or vectors.
Definition: cv.hpp:1