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