Posted by: sureshamrita | March 7, 2012

Boost multiarray – some examples

The following code shows how a 2D array can be manipulated using boost::multi_array. The code shows how to fill the array, find the row/column sum, display alternate elements, replace alternate elements etc. 

#include <boost/multi_array.hpp>
#include <iostream>
#include <numeric>
using namespace std;

int main() {
	const int rows = 3;
	const int cols = 5;
	typedef boost::multi_array<double, 2> array_type;
	typedef array_type::index index;
	array_type A(boost::extents[rows][cols]);

	array_type::element* itr = A.data();

	for (int i = 0; i < rows * cols; i++)
		*itr++ = i;

	cout << "displaying matrix" << endl;
	for (int i = 0; i < rows; i++) {
		for (int j = 0; j < cols; j++)
			cout << A[i][j] << " ";
		cout << endl;
	}
    cout << endl;
    
	cout << "row sum" << endl;
	for (int i = 0; i < rows; i++)
		cout << accumulate(A[i].begin(), A[i].end(), 0.0) << " ";
	cout << endl << endl;
	
	
	cout << "row sum - another method" << endl;
	typedef array_type::index_range range;
	for (int i = 0; i < rows; i++) {
		array_type::array_view<1>::type myview =
				A[boost::indices[i][range()]];
		cout << accumulate(myview.begin(), myview.end(), 0.0) << " ";
	}
	cout << endl << endl;
	
	cout << "col sum" << endl;
	for (int i = 0; i < cols; i++) {
		array_type::array_view<1>::type myview =
				A[boost::indices[range()][i]];
		cout << accumulate(myview.begin(), myview.end(), 0.0) << " ";
	}
	cout << endl << endl;
	
	cout << "displaying odd positioned  elements in a row" << endl;
	for (int i = 0; i < rows; i++) {
		array_type::array_view<1>::type myview =
				A[boost::indices[i][range(0,5,2)]];
		copy(myview.begin(),myview.end(),ostream_iterator<double>(cout," "));
		cout << endl;
	}
	cout << endl << endl;
	
	
	cout << "displaying even positioned  elements in a row" << endl;
	for (int i = 0; i < rows; i++) {
		array_type::array_view<1>::type myview =
				A[boost::indices[i][range(1,5,2)]];
		copy(myview.begin(),myview.end(),ostream_iterator<double>(cout," "));
		cout << endl;
	}
	cout << endl << endl;
	
	cout << "replacing even positioned  elements with -10 " << endl;
	for (int i = 0; i < rows; i++) {
		array_type::array_view<1>::type myview =
				A[boost::indices[i][range(1,5,2)]];
		fill(myview.begin(),myview.end(),-10);
	}
    cout << "displaying matrix" << endl;
	for (int i = 0; i < rows; i++) {
		for (int j = 0; j < cols; j++)
			cout << A[i][j] << " ";
		cout << endl;
	}
	cout << endl << endl;
	
	return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: