NumCpp  2.11.0
A Templatized Header Only C++ Implementation of the Python NumPy Library
cov.hpp
Go to the documentation of this file.
1 #pragma once
29 
30 #include <type_traits>
31 
34 #include "NumCpp/NdArray.hpp"
35 
36 namespace nc
37 {
38  //============================================================================
39  // Method Description:
51  template<typename dtype>
52  NdArray<double> cov(const NdArray<dtype>& x, bool bias = false)
53  {
55 
56  const auto varMeans = mean(x, Axis::COL);
57  const auto numVars = x.numRows();
58  const auto numObs = x.numCols();
59  const auto normilizationFactor = bias ? static_cast<double>(numObs) : static_cast<double>(numObs - 1);
60  using IndexType = typename std::remove_const<decltype(numVars)>::type;
61 
62  // upper triangle
63  auto covariance = NdArray<double>(numVars);
64  for (IndexType i = 0; i < numVars; ++i)
65  {
66  const auto var1Mean = varMeans[i];
67 
68  for (IndexType j = i; j < numVars; ++j)
69  {
70  const auto var2Mean = varMeans[j];
71 
72  double sum = 0.;
73  for (IndexType iObs = 0; iObs < numObs; ++iObs)
74  {
75  sum += (x(i, iObs) - var1Mean) * (x(j, iObs) - var2Mean);
76  }
77 
78  covariance(i, j) = sum / normilizationFactor;
79  }
80  }
81 
82  // fill in the rest of the symmetric matrix
83  for (IndexType j = 0; j < numVars; ++j)
84  {
85  for (IndexType i = j + 1; i < numVars; ++i)
86  {
87  covariance(i, j) = covariance(j, i);
88  }
89  }
90 
91  return covariance;
92  }
93 } // namespace nc
#define STATIC_ASSERT_ARITHMETIC(dtype)
Definition: StaticAsserts.hpp:39
size_type numCols() const noexcept
Definition: NdArrayCore.hpp:3418
size_type numRows() const noexcept
Definition: NdArrayCore.hpp:3430
constexpr auto j
Definition: Core/Constants.hpp:42
Definition: Cartesian.hpp:40
NdArray< double > cov(const NdArray< dtype > &x, bool bias=false)
Definition: cov.hpp:52
NdArray< dtype > sum(const NdArray< dtype > &inArray, Axis inAxis=Axis::NONE)
Definition: sum.hpp:46
NdArray< double > mean(const NdArray< dtype > &inArray, Axis inAxis=Axis::NONE)
Definition: mean.hpp:52