Search code examples
c++boostconstantsboost-ublas

Constant matrix with boost ublas


I would like to define a constant 3x3 matrix with boost like this and it will never change during the execution:

[1 2 3
 4 5 6
 7 8 9] 

This matrix will be a member of a class. So, can I define and initialize a constant matrix variable as a class member just like primitive types? When I try to type const for someMatrix variable, I could not assign matrix data in constructor and get this error:

error: assignment of read-only location '((Test*)this)->Test::someMatrix.boost::numeric::ublas::matrix<double>::operator()(0, 0)'

Here are codes:

Test.h

#ifndef TEST_H_
#define TEST_H_

#include <boost/numeric/ublas/matrix.hpp>

namespace bnu = boost::numeric::ublas;

class Test {
private:
    const double a = 1;
    const double b = 2;
    const double c = 3;
    const double d = 4;
    const double e = 5;
    const double f = 6;
    const double g = 7;
    const double h = 8;
    const double i = 9;
    const bnu::matrix<double> someMatrix;

public:
    Test();
    virtual ~Test();
};

#endif /* TEST_H_ */

Test.cpp

Test::Test(){
    someMatrix(0,0) = a;
}

Main.cpp

include "Test.h"

int main() {
    Test * t = new Test();

}

What I actually want is finding a way to define someMatrix like this:

const bnu::matrix<double> someMatrix(3,3) = {a,b,c,d,e,f,g,h,i};

Solution

  • You could write a helper function to do this

    class Test {
    private:
        const bnu::matrix<double> someMatrix;
        static bnu::matrix<double> initSomeMatrix();
    public:
        Test();
        virtual ~Test();
    }
    
    Test::Test() : someMatrix(initSomeMatrix()) {
    }
    
    bnu::matrix<double> Test::initSomeMatrix() {
        bnu::matrix<double> temp(3, 3);
        temp(0,0) = 1;
        ...
        return temp;
    }
    

    RVO should make this reasonably efficient.