How do I convert a arma::cx_mat
to an array of arrays?
The motivation for the conversion is to use libmatio
, which is a C library, to output a .mat file.
So far I have created a function to convert from arma:cx_mat
to a vector of vectors:
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;
}
If you need convert real part from cx_mat into C array of arrays can use this function:
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;
}
Note, need free the array when it is no longer needed. Example:
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.