blob: 1a377e56927ce046998e276fb8cb3be2ea1bba8c [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"
Wenzel Jakob8f4eb002015-10-15 18:13:33 +020012#include <pybind11/numpy.h>
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020013
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",
Wenzel Jakobb50872a2015-10-13 17:38:22 +020029 [](py::array_t<int> x, py::array_t<float> y, float z) {
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020030 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}