NumCpp  2.12.1
A Templatized Header Only C++ Implementation of the Python NumPy Library
nanmedian.hpp
Go to the documentation of this file.
1
28#pragma once
29
30#include <cmath>
31#include <vector>
32
36#include "NumCpp/Core/Shape.hpp"
37#include "NumCpp/Core/Types.hpp"
39#include "NumCpp/NdArray.hpp"
40
41namespace nc
42{
43 //============================================================================
44 // Method Description:
54 template<typename dtype>
56 {
58
59 switch (inAxis)
60 {
61 case Axis::NONE:
62 {
63 std::vector<dtype> values;
64 for (auto value : inArray)
65 {
66 if (!std::isnan(value))
67 {
68 values.push_back(value);
69 }
70 }
71
72 const uint32 middle = static_cast<uint32>(values.size()) / 2;
73 stl_algorithms::nth_element(values.begin(), values.begin() + middle, values.end());
74 NdArray<dtype> returnArray = { values[middle] };
75
76 return returnArray;
77 }
78 case Axis::COL:
79 {
80 const Shape inShape = inArray.shape();
81 NdArray<dtype> returnArray(1, inShape.rows);
82 for (uint32 row = 0; row < inShape.rows; ++row)
83 {
84 std::vector<dtype> values;
85 for (uint32 col = 0; col < inShape.cols; ++col)
86 {
87 if (!std::isnan(inArray(row, col)))
88 {
89 values.push_back(inArray(row, col));
90 }
91 }
92
93 const uint32 middle = static_cast<uint32>(values.size()) / 2;
94 stl_algorithms::nth_element(values.begin(), values.begin() + middle, values.end());
95 returnArray(0, row) = values[middle];
96 }
97
98 return returnArray;
99 }
100 case Axis::ROW:
101 {
102 return nanmedian(inArray.transpose(), Axis::COL);
103 }
104 default:
105 {
106 THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type.");
107 return {}; // get rid of compiler warning
108 }
109 }
110 }
111} // namespace nc
#define THROW_INVALID_ARGUMENT_ERROR(msg)
Definition: Error.hpp:37
#define STATIC_ASSERT_FLOAT(dtype)
Definition: StaticAsserts.hpp:50
Holds 1D and 2D arrays, the main work horse of the NumCpp library.
Definition: NdArrayCore.hpp:139
self_type transpose() const
Definition: NdArrayCore.hpp:4882
const Shape & shape() const noexcept
Definition: NdArrayCore.hpp:4511
A Shape Class for NdArrays.
Definition: Core/Shape.hpp:41
uint32 rows
Definition: Core/Shape.hpp:44
uint32 cols
Definition: Core/Shape.hpp:45
void nth_element(RandomIt first, RandomIt nth, RandomIt last) noexcept
Definition: StlAlgorithms.hpp:425
Definition: Cartesian.hpp:40
Axis
Enum To describe an axis.
Definition: Enums.hpp:36
bool isnan(dtype inValue) noexcept
Definition: isnan.hpp:49
NdArray< dtype > nanmedian(const NdArray< dtype > &inArray, Axis inAxis=Axis::NONE)
Definition: nanmedian.hpp:55
std::uint32_t uint32
Definition: Types.hpp:40