• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1A simple tutorial on Arrays
2===========================
3
4Let's start with a simple tutorial to create and modify arrays.
5
6Get the necessary headers for numpy components and set up necessary namespaces::
7
8	#include <boost/python/numpy.hpp>
9	#include <iostream>
10
11	namespace p = boost::python;
12	namespace np = boost::python::numpy;
13
14Initialise the Python runtime, and the numpy module. Failure to call these results in segmentation errors::
15
16	int main(int argc, char **argv)
17	{
18	  Py_Initialize();
19	  np::initialize();
20
21
22Zero 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::
23
24	  p::tuple shape = p::make_tuple(3, 3);
25	  np::dtype dtype = np::dtype::get_builtin<float>();
26	  np::ndarray a = np::zeros(shape, dtype);
27
28You can also create an empty array like this ::
29
30	np::ndarray b = np::empty(shape,dtype);
31
32Print 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< >::
33
34	  std::cout << "Original array:\n" << p::extract<char const *>(p::str(a)) << std::endl;
35
36	  // Reshape the array into a 1D array
37	  a = a.reshape(p::make_tuple(9));
38	  // Print it again.
39	  std::cout << "Reshaped array:\n" << p::extract<char const *>(p::str(a)) << std::endl;
40	}
41
42