How do I convert an armadillo matrix to a vector of vectors?

前端 未结 1 1712
闹比i
闹比i 2021-02-05 12:59

I created an armadillo c++ matrix as follows:

arma::mat A; 
A.zeros(3,4);

I want to convert it to a vector of vectors defined by



        
1条回答
  •  面向向阳花
    2021-02-05 13:37

    In such cases you should use arma::conv_to which is a totally superb feature of arma.

    Note that this method will require from a source object to be able to be interpreted as a vector. That is why we need to do this iteratively for every row. Here is a conversion method:

    #include 
    
    typedef std::vector stdvec;
    typedef std::vector< std::vector > stdvecvec;
    
    stdvecvec mat_to_std_vec(arma::mat &A) {
        stdvecvec V(A.n_rows);
        for (size_t i = 0; i < A.n_rows; ++i) {
            V[i] = arma::conv_to< stdvec >::from(A.row(i));
        };
        return V;
    }
    

    And here is an exemplary usage:

    #include 
    #include 
    
    int main(int argc, char **argv) {
        arma::mat A = arma::randu(5, 5);
        std::cout << A << std::endl;
    
        stdvecvec V = mat_to_std_vec(A);
        for (size_t i = 0; i < V.size(); ++i) {
            for (size_t j = 0; j < V[i].size(); ++j) {
                std::cout << "   "
                    << std::fixed << std::setprecision(4) << V[i][j];
            }
            std::cout << std::endl;
        }
        return 0;
    }
    

    std::setprecision used to generate more readable output:

    0.8402   0.1976   0.4774   0.9162   0.0163
    0.3944   0.3352   0.6289   0.6357   0.2429
    0.7831   0.7682   0.3648   0.7173   0.1372
    0.7984   0.2778   0.5134   0.1416   0.8042
    0.9116   0.5540   0.9522   0.6070   0.1567
    
    0.8402   0.1976   0.4774   0.9162   0.0163
    0.3944   0.3352   0.6289   0.6357   0.2429
    0.7831   0.7682   0.3648   0.7173   0.1372
    0.7984   0.2778   0.5134   0.1416   0.8042
    0.9116   0.5540   0.9522   0.6070   0.1567
    

    Have a good one!

    0 讨论(0)
提交回复
热议问题