Reputation: 3
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 :)
Upvotes: 0
Views: 83
Reputation: 3260
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.
Upvotes: 1