Skip to content

Commit f4c6817

Browse files
authored
Merge pull request #2840 from stan-dev/feature/vectorize-minus
Allow stan::math::minus on std::vectors
2 parents 4d48730 + 5522b9d commit f4c6817

3 files changed

Lines changed: 26 additions & 1 deletion

File tree

stan/math/prim/fun/minus.hpp

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
#define STAN_MATH_PRIM_FUN_MINUS_HPP
33

44
#include <stan/math/prim/meta.hpp>
5+
#include <stan/math/prim/functor/apply_vector_unary.hpp>
56

67
namespace stan {
78
namespace math {
@@ -13,11 +14,24 @@ namespace math {
1314
* @param x Subtrahend.
1415
* @return Negation of subtrahend.
1516
*/
16-
template <typename T>
17+
template <typename T, require_not_std_vector_t<T>* = nullptr>
1718
inline auto minus(const T& x) {
1819
return -x;
1920
}
2021

22+
/**
23+
* Return the negation of the each element of a vector
24+
*
25+
* @tparam T Type of container.
26+
* @param x Container.
27+
* @return Container where each element is negated.
28+
*/
29+
template <typename T>
30+
inline auto minus(const std::vector<T>& x) {
31+
return apply_vector_unary<std::vector<T>>::apply(
32+
x, [](const auto& v) { return -v; });
33+
}
34+
2135
} // namespace math
2236
} // namespace stan
2337

test/unit/math/mix/fun/minus_test.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,9 @@ TEST(MathMixMatFun, minus) {
3939
for (const auto& y : std::vector<Eigen::MatrixXd>{u00, u11, u22, u23}) {
4040
stan::test::expect_ad(f, y);
4141
}
42+
43+
Eigen::MatrixXd v22(2, 2);
44+
v22 << 5, 6, 7, 8;
45+
std::vector<Eigen::MatrixXd> vec_mat{u22, v22};
46+
stan::test::expect_ad(f, vec_mat);
4247
}

test/unit/math/prim/fun/minus_test.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,9 @@ TEST(MathMatrixPrimMat, minus) {
1010
EXPECT_EQ(0, stan::math::minus(rv0).size());
1111
EXPECT_EQ(0, stan::math::minus(m0).size());
1212
}
13+
14+
TEST(MathMatrixPrimMat, vectorized_minus) {
15+
// test int->int
16+
std::vector<int> u{1, 2, 3, 4};
17+
std::vector<int> v = stan::math::minus(u);
18+
}

0 commit comments

Comments
 (0)