Replace Numerical Recipe's dmatrix with a C++ class

578 views Asked by At

I'm revamping an old application that use Numerical Recipes' dmatrix quite extensively. Since one of the reasons I'm working on the application is because its code is about to be opened, I want to replace all of the Numerical Recipes code with code that can be freely distributed.

dmatrix is a function that returns a matrix of doubles. The called supplies the lower and upper bound for each index, like so:

double **mat = dmatrix(1,3,1,3);

mat now has 3 rows, from 1 to 3, and 3 columns, from 1 to 3, so that mat[1][1] is the first element and mat[3][3] is the last.

I looked at various C++ matrix implementations, none of them allowed me to specify the lower bound of each dimension. Is there something I can use, or do I have to write yet another matrix class for this?

1

There are 1 answers

3
Guilherme Bernal On

I believe that you can easily make a wrapper of some other matrix implementation to add the lower bound feature. Example (untested):

class Matrix {
    OtherMatrix m;
    int lowerX, lowerY;
public:

    Matrix(int lx, int hx, int ly, int hy) :
        m(hx-lx, hy-ly),
        lowerX(lx), lowerY(ly) { }

    MatrixCol operator[] (int x) {
        return {this, x};
    } 
};

class MatrixCol {
    friend class Matrix;
    Matrix* mm;
    int x;
public:
    double& operator[] (int y) {
        return mm->m[x - mm->lowerX, y - mm->lowerY];
    } 
};

This may require a little more robust implementation depending on your use case. But this is the basic idea, expand from it.