c++ - Get submatrix of matrix with smaller size -
i representing map ( matrix rows x columns ) bits using bitset stl or dynamic_bitset<> boost ( can use whatever want ). need submatrix of matrix smaller size( example a(2,2) a(2,3) a(3,2) a(3,3) there size 2 ). there efficient structure representing matrix bits , getting submatrix startindex , length without iteration ?
it possible efficiently share data between matrices , submatrices. trick track 3 variables in class.
- row_stride
- start
- data
the data
needs shared_ptr
structure underlying data can destroyed once done it. start
pointer data referenced data
, row_stride
tells how far move next row.
additional things might track
- column stride (this can allow take other interesting views matrix, , support transpose efficiently).
- row , column length - these can handy debugging or if want make loops, , multiplies easier work with.
here's how might non-bit based approach (i've omitted .. gist).
template<typename t> struct matrixdata { t * data; explicit matrixdata( size_t n ) { new t[n]; } ~matrixdata() { delete [] data; } private: matrixdata( const matrixdata & ); matrixdata& operator=( const matrixdata & ); }; template<typename t> class matrix { matrix(size_t nni, size_t nnj) : data( new matrixdata( nni*nnj ) ), ni(nni), nj(nnj), row_stride(ni), col_stride(1) { } t operator()( size_t i, size_t j) { assert( < ni ); assert( j < nj ); return start + * col_stride + j * row_stride; } matrix submatrix( size_t i_start, size_t j_start, size_t new_ni, size_t new_nj ) { assert( i_start + new_ni < ni ); assert( j_start + new_nj < nj ); matrix retval(*this); retval.start += i_start * col_stride + j_start * row_stride; retval.ni = new_ni; retval.nj = new_nj; return retval; } matrix transpose() { matrix retval(*this); std::swap(retval.ni,retval.nj); std::swap(retval.row_stride,retval.col_stride); } private: shared_ptr<matrixdata> data; t* start; size_t ni; size_t nj; size_t row_stride; size_t col_stride; };
making work bit based version mean changing matrixdata
hold 1 of bot based structures, changing start
index structure , changing operator()
access data correctly.
Comments
Post a Comment