blob: 4a0339776a78089912ddf90dad9c38aeb61329ce [file] [log] [blame]
Wenzel Jakobd4258ba2015-07-26 16:33:49 +02001/*
Wenzel Jakoba576e6a2015-07-29 17:51:54 +02002 example/example10.cpp -- auto-vectorize functions over NumPy array
3 arguments
Wenzel Jakobd4258ba2015-07-26 16:33:49 +02004
5 Copyright (c) 2015 Wenzel Jakob <wenzel@inf.ethz.ch>
6
7 All rights reserved. Use of this source code is governed by a
8 BSD-style license that can be found in the LICENSE file.
9*/
10
11#include "example.h"
12#include <pybind/numpy.h>
13
14double my_func(int x, float y, double z) {
15 std::cout << "my_func(x:int=" << x << ", y:float=" << y << ", z:float=" << z << ")" << std::endl;
16 return x*y*z;
17}
18
Wenzel Jakob43398a82015-07-28 16:12:20 +020019std::complex<double> my_func3(std::complex<double> c) {
20 return c * std::complex<double>(2.f);
21}
22
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020023void init_ex10(py::module &m) {
Wenzel Jakoba576e6a2015-07-29 17:51:54 +020024 // Vectorize all arguments of a function (though non-vector arguments are also allowed)
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020025 m.def("vectorized_func", py::vectorize(my_func));
Wenzel Jakoba576e6a2015-07-29 17:51:54 +020026
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020027 // Vectorize a lambda function with a capture object (e.g. to exclude some arguments from the vectorization)
28 m.def("vectorized_func2",
29 [](py::array_dtype<int> x, py::array_dtype<float> y, float z) {
30 return py::vectorize([z](int x, float y) { return my_func(x, y, z); })(x, y);
31 }
32 );
Wenzel Jakoba576e6a2015-07-29 17:51:54 +020033
34 // Vectorize a complex-valued function
Wenzel Jakob43398a82015-07-28 16:12:20 +020035 m.def("vectorized_func3", py::vectorize(my_func3));
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020036}