NumCpp  2.10.1
A Templatized Header Only C++ Implementation of the Python NumPy Library
fromfunction.hpp
Go to the documentation of this file.
1 #pragma once
29 
30 #include <functional>
31 #include <numeric>
32 #include <vector>
33 
35 #include "NumCpp/Core/Shape.hpp"
36 #include "NumCpp/NdArray.hpp"
37 
38 namespace nc
39 {
40  //============================================================================
41  // Method Description:
52  template<typename dtype>
53  NdArray<dtype> fromfunction(const std::function<dtype(typename NdArray<dtype>::size_type)> func,
55  {
56  NdArray<dtype> result(1, size);
57  const auto indices = [size]
58  {
59  std::vector<typename NdArray<dtype>::size_type> temp(size);
60  std::iota(temp.begin(), temp.end(), 0);
61  return temp;
62  }();
63 
64  stl_algorithms::transform(indices.begin(),
65  indices.end(),
66  result.begin(),
67  [&func](const auto idx) { return func(idx); });
68 
69  return result;
70  }
71 
72  //============================================================================
73  // Method Description:
84  template<typename dtype>
86  const std::function<dtype(typename NdArray<dtype>::size_type, typename NdArray<dtype>::size_type)> func,
87  Shape shape)
88  {
89  NdArray<dtype> result(shape);
90  const auto rows = [&shape]
91  {
92  std::vector<typename NdArray<dtype>::size_type> temp(shape.rows);
93  std::iota(temp.begin(), temp.end(), 0);
94  return temp;
95  }();
96  const auto cols = [&shape]
97  {
98  std::vector<typename NdArray<dtype>::size_type> temp(shape.cols);
99  std::iota(temp.begin(), temp.end(), 0);
100  return temp;
101  }();
102 
103  stl_algorithms::for_each(rows.begin(),
104  rows.end(),
105  [&cols, &result, &func](const auto row)
106  {
107  stl_algorithms::transform(cols.begin(),
108  cols.end(),
109  result.begin(row),
110  [&func, row](const auto col) { return func(row, col); });
111  });
112 
113  return result;
114  }
115 } // namespace nc
Holds 1D and 2D arrays, the main work horse of the NumCpp library.
Definition: NdArrayCore.hpp:138
iterator begin() noexcept
Definition: NdArrayCore.hpp:1258
uint32 size_type
Definition: NdArrayCore.hpp:155
A Shape Class for NdArrays.
Definition: Core/Shape.hpp:41
uint32 rows
Definition: Core/Shape.hpp:44
uint32 cols
Definition: Core/Shape.hpp:45
OutputIt transform(InputIt first, InputIt last, OutputIt destination, UnaryOperation unaryFunction)
Definition: StlAlgorithms.hpp:775
void for_each(InputIt first, InputIt last, UnaryFunction f)
Definition: StlAlgorithms.hpp:225
Definition: Coordinate.hpp:45
uint32 size(const NdArray< dtype > &inArray) noexcept
Definition: size.hpp:43
Shape shape(const NdArray< dtype > &inArray) noexcept
Definition: Functions/Shape.hpp:42
NdArray< dtype > fromfunction(const std::function< dtype(typename NdArray< dtype >::size_type)> func, typename NdArray< dtype >::size_type size)
Definition: fromfunction.hpp:53