Boost logo

Ublas :

Subject: [ublas] Matrix 'View' class
From: Andy Somogyi (somogyie_at_[hidden])
Date: 2010-07-27 12:11:56


Hello All

I frequently work where an external routine gives me a block of memory that I need to access as a 2 dimensional matrix (row-major).

I've written a 'matrix-view' class attached below. I plan on just reading and writing to the memory block (that I don't own) using this view class. I've tested it with a variety of test cases (reading, writing, assigning to and from other matrices), and have not come into any problems. Would you guys care to take a look at this class, and let me know if there are any potential problems with this design, and I think a class like this would be of great utility to boost, any possibilities of submitting it?

thanks.

namespace boost { namespace numeric { namespace ublas {

template<class T, class L=row_major >
/**
* a temporary 'view' of an existing 2-dimensional block of
* memory.
*/
class matrix_view : public matrix<T, L, shallow_array_adaptor<T> > {
        typedef typename shallow_array_adaptor<T>::size_type size_type;
        typedef matrix<T, L, shallow_array_adaptor<T> > base_type;
public:
        /**
         * create a matrix_view that is a view of an existing block of data.
         * the matrix_view does NOT own the given pointer, user is responsible
         * for making sure that this class is not used after the p_data
         * block has been freed.
         */
        matrix_view (size_type size1, size_type size2, T* p_data) :
                base_type(size1, size2, shallow_array_adaptor<T>(size1*size2, p_data)) {};
        
private:
        /**
         * hide ctors of base class, can only have a matrix_view that is attached to
         * an existing block of data.
         */
        matrix_view() {};
        matrix_view(size_type size1, size_type size2) {};
};
}}};

// example of use, assign identity matrix to given data block,
// assuming rows == columns.
void myFunc(int rows, int columns, double* pData) {
        matrix_view<double> mv(rows,colums,pData);
        identity_matrix<double> i(rows);
        mv = i; // the data block referenced by pData is now initialized to the identity matrix.
}