0

My class is

 class aMatrix { private: std::vector<std::vector<double> > mat; unsigned rows; unsigned cols; ...} 

I want to merge two matrixes using method

aMatrix aMatrix::merge(const aMatrix& ob){ this->mat.reserve(this->mat.size()+ob.mat.size()); this->cols+=ob.cols; this->mat.insert(this->mat.end(), ob.mat.begin(),ob.mat.end()); return *this; } 

but it doesnt work. Any ideas how to make it work?

edit: there's no error. it just adds column of ~0 and then values than differ from ob.mat.

edit:

aMatrix mat1(3,3); mat1(0, 0) = 1; mat1(0, 1) = 1; mat1(0, 2) = 1; mat1(1, 0) = 2; mat1(1, 1) = 3; mat1(1, 2) = 5; mat1(2, 0) = 11; mat1(2, 1) = 0; mat1(2, 2) = 5; aMatrix ones(3,3); ones(0,0)=1; ones(1,1)=1; ones(2,2)=1; mat1.merge(ones); 

the result is:

1, 1, 1, 1.11319e-308, 2, 3, 2, 3, 5, 1.11318e-308, 11, 0, 11, 0, 5, 1.11317e-308, 1, 0, 

edit: How to make it work in such notation?

// Parameter Constructor aMatrix::aMatrix(unsigned _rows, unsigned _cols, const double& _initial) { mat.resize(_rows); for (unsigned i = 0; i < mat.size(); i++) { mat[i].resize(_cols, _initial); } rows = _rows; cols = _cols; } 

edit: OK, it works now. right code:

aMatrix& aMatrix::merge(const aMatrix& ob){ this->mat.reserve(this->mat.size()+ob.mat.size()); this->cols+=ob.cols; for (unsigned i = 0; i < this->mat.size(); i++) { this->mat[i].insert(this->mat[i].end(), ob.mat[i].begin(),ob.mat[i].end() ); } return *this; } 

thanks :)

2
  • can you provide a minimum working code that reproduces the error? Commented Apr 18, 2015 at 18:05
  • Aside: You probably meant for the return value to be aMatrix&, not aMatrix. Commented Apr 18, 2015 at 19:17

1 Answer 1

1

You should do the merge row by row. What you are doing in your code is adding more rows to the original matrix. What you are intended to do is add more columns to the original matrix.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah, nice catch. And here I was wondering why my code was running fine: ideone.com/UFJlCa .
@coyotte508, your are using a column-major way, then it's fine.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.