将arma::cx_mat转换为数组数组

Convert arma::cx_mat to array of arrays

本文关键字:数组 转换 mat arma cx      更新时间:2023-10-16

如何将arma::cx_mat转换为数组?

转换的动机是使用libmatio(一个C库)来输出.mat文件。

到目前为止,我已经创建了一个函数来将arma:cx_mat转换为矢量的矢量:

std::vector<std::vector<double>> mat_to_vv(arma::cx_mat &M)
{
    std::vector<std::vector<double>> vv(M.n_rows);
    for(size_t i=0; i<M.n_rows; ++i)
    {
        vv[i] = arma::conv_to<std::vector<double>>::from(M.row(i));
    };
    return vv;
}

如果您需要将实际部分从cx_mat转换为数组的C数组,可以使用此函数:

double** mat_to_carr(arma::cx_mat &M,std::size_t &n,std::size_t &m)
{
const std::size_t nrows = M.n_rows;
const std::size_t ncols = M.n_cols;
double **array = (double**)malloc(nrows * sizeof(double *));
for(std::size_t i = 0; i < nrows; i++)
    {
        array[i] = (double*)malloc(ncols * sizeof(double));
        for (std::size_t j = 0; j < ncols; ++j)
            array[i][j] = M(i + j*ncols).real();
    }
n = nrows;
m = ncols;
return array;
}

请注意,不再需要时需要释放数组。示例:

int main()
{
cx_mat X(5, 5, fill::randn);
std::size_t n,m;
auto array = mat_to_carr(X,n,m);
for (std::size_t i = 0; i <  n; ++i)
    {
      for (std::size_t j = 0; j < m; ++j)
          std::cout<<array[i][j]<<" ";
      std::cout<<std::endl;
    }
for(std::size_t i = 0; i <  n; i++)
        free(array[i]);
free(array);
return 0;
}