Reputation: 397
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};
Upvotes: 1
Views: 1017
Reputation: 87959
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.
Upvotes: 1
Reputation: 2765
Using <boost/numeric/ublas/assignment.hpp>
you can insert values into an ublas::matrix
or ublas::vector
using <<=
which allows you instatiate your matrix like so:
bnu::matrix<double> a(3,3); a <<= 0, 1, 2,
3, 4, 5,
6, 7, 8;
To make it constant just copy it:
const bnu::matrix<double> b = a;
HERE is a working minimal example copied from here
Upvotes: 6