NumCpp  2.18.0
A Templatized Header Only C++ Implementation of the Python NumPy Library
Loading...
Searching...
No Matches
nanmedian.hpp
Go to the documentation of this file.
1
28#pragma once
29
30#include <cmath>
31#include <vector>
32
35#include "NumCpp/Core/Shape.hpp"
36#include "NumCpp/Core/Types.hpp"
37#include "NumCpp/NdArray.hpp"
38
39namespace nc
40{
41 //============================================================================
42 // Method Description:
52 template<typename dtype>
54 {
56
57 switch (inAxis)
58 {
59 case Axis::NONE:
60 {
61 std::vector<dtype> values;
62 for (auto value : inArray)
63 {
64 if (!std::isnan(value))
65 {
66 values.push_back(value);
67 }
68 }
69
70 const uint32 middle = static_cast<uint32>(values.size()) / 2;
71 stl_algorithms::nth_element(values.begin(), values.begin() + middle, values.end());
72 NdArray<dtype> returnArray = { values[middle] };
73
74 return returnArray;
75 }
76 case Axis::COL:
77 {
78 const Shape inShape = inArray.shape();
79 NdArray<dtype> returnArray(1, inShape.rows);
80 for (uint32 row = 0; row < inShape.rows; ++row)
81 {
82 std::vector<dtype> values;
83 for (uint32 col = 0; col < inShape.cols; ++col)
84 {
85 if (!std::isnan(inArray(row, col)))
86 {
87 values.push_back(inArray(row, col));
88 }
89 }
90
91 const uint32 middle = static_cast<uint32>(values.size()) / 2;
92 stl_algorithms::nth_element(values.begin(), values.begin() + middle, values.end());
93 returnArray(0, row) = values[middle];
94 }
95
96 return returnArray;
97 }
98 case Axis::ROW:
99 {
100 return nanmedian(inArray.transpose(), Axis::COL);
101 }
102 default:
103 {
104 THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type.");
105 return {}; // get rid of compiler warning
106 }
107 }
108 }
109} // 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:135
self_type transpose() const
Definition NdArrayCore.hpp:4959
const Shape & shape() const noexcept
Definition NdArrayCore.hpp:4587
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:426
Definition Cartesian.hpp:39
Axis
Enum To describe an axis.
Definition Enums.hpp:36
@ ROW
Definition Enums.hpp:38
@ COL
Definition Enums.hpp:39
@ NONE
Definition Enums.hpp:37
std::uint32_t uint32
Definition Types.hpp:40
NdArray< dtype > nanmedian(const NdArray< dtype > &inArray, Axis inAxis=Axis::NONE)
Definition nanmedian.hpp:53