NumCpp  2.14.0
A Templatized Header Only C++ Implementation of the Python NumPy Library
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
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
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
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
Holds 1D and 2D arrays, the main work horse of the NumCpp library.
Definition NdArrayCore.hpp:139
size_type numCols() const noexcept
Definition NdArrayCore.hpp:3541
size_type numRows() const noexcept
Definition NdArrayCore.hpp:3553
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 > arange(dtype inStart, dtype inStop, dtype inStep=1)
Definition arange.hpp:59
NdArray< dtype > sum(const NdArray< dtype > &inArray, Axis inAxis=Axis::NONE)
Definition sum.hpp:46
Bias
Bias boolean.
Definition Enums.hpp:65