simple.rst 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. A simple tutorial on Arrays
  2. ===========================
  3. Let's start with a simple tutorial to create and modify arrays.
  4. Get the necessary headers for numpy components and set up necessary namespaces::
  5. #include <boost/python/numpy.hpp>
  6. #include <iostream>
  7. namespace p = boost::python;
  8. namespace np = boost::python::numpy;
  9. Initialise the Python runtime, and the numpy module. Failure to call these results in segmentation errors::
  10. int main(int argc, char **argv)
  11. {
  12. Py_Initialize();
  13. np::initialize();
  14. Zero filled n-dimensional arrays can be created using the shape and data-type of the array as a parameter. Here, the shape is 3x3 and the datatype is the built-in float type::
  15. p::tuple shape = p::make_tuple(3, 3);
  16. np::dtype dtype = np::dtype::get_builtin<float>();
  17. np::ndarray a = np::zeros(shape, dtype);
  18. You can also create an empty array like this ::
  19. np::ndarray b = np::empty(shape,dtype);
  20. Print the original and reshaped array. The array a which is a list is first converted to a string, and each value in the list is extracted using extract< >::
  21. std::cout << "Original array:\n" << p::extract<char const *>(p::str(a)) << std::endl;
  22. // Reshape the array into a 1D array
  23. a = a.reshape(p::make_tuple(9));
  24. // Print it again.
  25. std::cout << "Reshaped array:\n" << p::extract<char const *>(p::str(a)) << std::endl;
  26. }