drunnels
asked on
dyanmic matrix
I want to write a class to efficiently implement a matrix. The size has
to be dynamic.
I would like a two dimensional array, but the pointer arithmetic won't work because I want both dimenions to be dynamic.
class Matrix {
private:
int rows, cols;
double** ptr;
public:
Matrix(int r, int c) : rows(r), cols(c) {
ptr = new double[r][c];
}
};
I am considering an array of pointers to rows because the above is not
working. What's a better way to do it?
Thanks
Dave
to be dynamic.
I would like a two dimensional array, but the pointer arithmetic won't work because I want both dimenions to be dynamic.
class Matrix {
private:
int rows, cols;
double** ptr;
public:
Matrix(int r, int c) : rows(r), cols(c) {
ptr = new double[r][c];
}
};
I am considering an array of pointers to rows because the above is not
working. What's a better way to do it?
Thanks
Dave
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
The first case that jkr points out is quite slow, which is why it is not typically used in high performance applications, which you said you wanted.
On the other hand, if a lot of the matrix is empty, then a sparse implementation wlil be better. In no case will a full array of pointers be worthwhile.
Noteworthy cases that can be optmized include diagonal, tridiagonal, triangular, and sparse, for which you can find code on that web site to which I referred you.
On the other hand, if a lot of the matrix is empty, then a sparse implementation wlil be better. In no case will a full array of pointers be worthwhile.
Noteworthy cases that can be optmized include diagonal, tridiagonal, triangular, and sparse, for which you can find code on that web site to which I referred you.
class Matrix1 {
private:
int rows, cols;
double** ptr;
public:
Matrix1(int r, int c) : rows(r), cols(c) {
ptr = new double*[r];
for (int i = 0; i < r; ++i) ptr[i] = new double[c];
}
};
class Matrix2 {
private:
int rows, cols;
double* ptr;
public:
Matrix2(int r, int c) : rows(r), cols(c) {
ptr = new double[r * c];
}
};
In the latter case, all you have to do is keeping in mind that m(i,j) is actually 'ptr[i *cols + j]'