如何将犰狳矩阵转换为向量向量? [英] How do I convert an armadillo matrix to a vector of vectors?

查看:261
本文介绍了如何将犰狳矩阵转换为向量向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了如下犰狳c ++矩阵:

I created an armadillo c++ matrix as follows:

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

我想将其转换为

std::vector< std::vector<double> > B(3, std::vector<double>(4) ); 

如何将B设置为等于A?如果没有简单的矢量向量的方法,那么数组的数组呢,即,如果我将B定义为

How do I set B to equal A? If there is not an easy way for a vector of vectors, what about an array of arrays, i.e., what if I defined B to be

double B[3][4]; 

推荐答案

在这种情况下,您应该使用 arma::conv_to 这是arma的绝佳功能.

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 <armadillo>

typedef std::vector<double> stdvec;
typedef std::vector< std::vector<double> > 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;
}

这是一个示例用法:

#include <iomanip>
#include <iostream>

int main(int argc, char **argv) {
    arma::mat A = arma::randu<arma::mat>(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用于生成更具可读性的输出:

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

有一个好人!

这篇关于如何将犰狳矩阵转换为向量向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆