Boost logo

Ublas :

Subject: Re: [ublas] Is it possible to construct alternative "views" of vectors and matrices?
From: Mark Johnson (mj1_at_[hidden])
Date: 2009-09-17 13:11:59


Thanks Jesse for your answer and the code fragment!

Is there a way of building a matrix or vector out of a pre-existing
array_type? I'd like to be able to view a matrix as a vector, and use
vector arithmetic on it.

What would be great would be a way of building a matrix or vector out of
any object v that implements (say) v.size() and v[index].

I also think it would be great to have "computed matrices", i.e., an
adaptor that constructs a matrix interface for an arbitrary function
object f that implements (say) f.size1(), f.size2() and f(i,j).

I'd be willing to implement such a thing, but I don't know whether the
returned object should be a matrix_expression, a matrix_reference or
whatever, and I don't know what things an object has to define in order
to be a vector or a matrix. If someone can point me to the appropriate
documentation that would be great!

Best,

Mark

On 01/-10/-28163 02:59 PM, Jesse Manning wrote:
> For dense matrix types the underlying storage of the matrix is just an
> array of m*n values. You can access this data directly from the matrix
> and it will provide the "vector view" so to speak. I am not sure about
> other types of matrices such as sparse or compressed since I have
> mostly dealt with dense. Here is some example code:
>
> ublas::matrix<int> mat1(3,3);
>
> // fill matrix with values
> mat1(0,0) = 1;
> mat1(0,1) = 3;
> mat1(0,2) = 2;
> mat1(1,0) = 1;
> mat1(1,1) = 0;
> mat1(1,2) = 0;
> mat1(2,0) = 1;
> mat1(2,1) = 2;
> mat1(2,2) = 2;
>
> // get vector view of matrix elements
> ublas::matrix<int>::array_type& myarray = mat1.data();
>
> // print contents
> std::cout<< "myarray size: "<< myarray.size()<< std::endl;
> std::cout<< "[";
> for (size_t i=0; i< myarray.size(); ++i)
> {
> std::cout<< myarray[i];
>
> if (i != myarray.size()-1)
> {
> std::cout<< ",";
> }
> }
> std::cout<< "]"<< std::endl;
>
> // modify some contents of the matrix using the vector view
> myarray[0] = 0;
> myarray[1] = 0;
> myarray[2] = 0;
>
> // print contents to show changes
> std::cout<< "myarray size: "<< myarray.size()<< std::endl;
> std::cout<< "[";
> for (size_t i=0; i< myarray.size(); ++i)
> {
> std::cout<< myarray[i];
>
> if (i != myarray.size()-1)
> {
> std::cout<< ",";
> }
> }
> std::cout<< "]"<< std::endl;