Search code examples
c++armadillo

How to generate this matrix with armadillo in c++?


I would like to generate a matrix in C ++ using armadillo that behaves like a "truth table", for example:

0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1

I was thinking of a cycle of this kind, but I'm not very practical with armadillo and its data structures.

imat A = zeros<imat>(8, 3);

/* fill each row */
for(int i=0; i < 8; i++)
{
    A.row(i) = (i/(pow(2, i)))%2 * ones<ivec>(3).t();  // 
}

cout << "A = \n" << A << endl;

Any ideas?


Solution

  • If you need a large size truth table matrix (~2^30 x 30) as you said here, from the memory point of view, you should implement a function which quickly calculates the values you want rather than storing them on a matrix.

    This is easily done using std::bitset as follows. Note that N must be determined at compile-time in this method. Then you can get the value of your A(i,j) by matrix<3>(i,j):

    DEMO

    #include <bitset>
    
    template <std::size_t N>
    std::size_t matrix(std::size_t i, std::size_t j)
    {
        return std::bitset<N>(i)[N-j-1];
    }