Boost logo

Boost Users :

From: Edward Grace (ej.grace_at_[hidden])
Date: 2006-11-20 06:37:45


Following my original request:

>> Is it possible to adapt e.g. a pointer to double in to a
>> ublas::matrix<double>, or construct a matrix from a pointer to
>> double?

And the following suggestion,

> You could write your own storage class (see the Storage concept in
> the uBLAS documentation) which is an adaptor for a pointer and you
> can assign set the pointer via the data() member function of
> matrix<double>.
>
> --
> François Duranleau
> LIGUM, Université de Montréal
>

I have found the following seems to work. That said I would like
comments on this solution. Is this the "right" way to achieve what I
want? If not, what is?

If this is the best way, I recommend adding a note to the
ublas:....matrix|vector documentation to this effect, perhaps with
something like this as an example. I imagine that this would be a
common requirement for many people.

Regards,

-ed

/**
*
* Example of constructing a boost matrix and vector object from
* previously allocated heap memory using an array_adaptor.
*
* Comments please on the legitamacy of this and potential catches.
*
* ej.grace_at_[hidden]
*/

// Why should I have to define the following in order to use
// shallow_array_adaptor?
#define BOOST_UBLAS_SHALLOW_ARRAY_ADAPTOR

// Definitions for vector and matrix.
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <iostream>

int main() {
   using namespace boost::numeric::ublas;

   unsigned int N=100,M=200;
   double *data_vector, *data_matrix;
   data_vector = new double[N];
   data_matrix = new double[N*M];

   // Set Mat(0,1) to -Pi.
   data_matrix[1] = -3.14159;

   // Crate a boost vector object using the data_vector as storage.
   vector<double,shallow_array_adaptor<double> > Vec
(N,shallow_array_adaptor<double>(N,data_vector) );

   // Create a boost matrix object using the data_matrix pointer as
storage.
   matrix<double,row_major, shallow_array_adaptor<double> > Mat
(N,M,shallow_array_adaptor<double>(N*M,data_matrix) );
   Mat(3,3) = 3.0;

   // Should print -3.14159, 3
   std::cout << Mat(0,1) << "," << Mat(3,3) << std::endl;

   return 0;
};


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net