将Armadillo矩阵转换为Eigen MatriXd,反之亦然 [英] Converting an Armadillo Matrix to an Eigen MatriXd and vice versa
问题描述
如何从Armadillo Matrix转换为Eigen MatrixXd,反之亦然?
How can I convert from an Armadillo Matrix to an Eigen MatrixXd and vice versa?
我将nu
作为大小为N
的arma::vec
,将z
作为大小为N x 3
的arma::mat
.我想计算一个矩阵P
,例如条目P_ij
是
I have nu
as an arma::vec
of size N
, z
as arma::mat
of dimension N x 3
. I want to compute a matrix P
such as the entry P_ij
is
Pij=exp(nu(i) + nu(j) + z.row(j)*z.row(j)))
因此我使用了这段代码
int N=z.n_rows;
mat P= exp(nu*ones(1,N) + one(N,1)*(nu.t()) + z*(z.t()));
但是计算时间太长.特别是对于N = 50,000
来说,运行时间太长了.
But the computation takes too long. In particular, for N = 50,000
the run time is far to high.
使用Eigen似乎可以更快.但是我的矩阵是犰狳.如何使用本征运算?或者如何更快地执行此操作.
It seems that using Eigen can be faster. But my matrix are Armadillo. How can I use Eigen operations ? Or how can I do this operation faster.
推荐答案
使用 armadillo .memptr()
类成员函数,我们能够提取内存指针.在这里,我们可以使用特征的本征矩阵.
现在,我们可以使用特征的内存结构.然后,使用arma::mat
的高级构造函数选项,我们可以创建矩阵.
Now, we can go from the Eigen matrix using the .data()
member function to extract a point to Eigen's memory structure. Then, using the advanced constructor options of arma::mat
we can create an armadillo matrix.
例如:
#include <RcppArmadillo.h>
#include <RcppEigen.h>
// [[Rcpp::depends(RcppEigen)]]
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
Eigen::MatrixXd example_cast_eigen(arma::mat arma_A) {
Eigen::MatrixXd eigen_B = Eigen::Map<Eigen::MatrixXd>(arma_A.memptr(),
arma_A.n_rows,
arma_A.n_cols);
return eigen_B;
}
// [[Rcpp::export]]
arma::mat example_cast_arma(Eigen::MatrixXd eigen_A) {
arma::mat arma_B = arma::mat(eigen_A.data(), eigen_A.rows(), eigen_A.cols(),
false, false);
return arma_B;
}
/***R
(x = matrix(1:4, ncol = 2))
example_cast_eigen(x)
example_cast_arma(x)
*/
结果:
(x = matrix(1:4, ncol = 2))
# [,1] [,2]
# [1,] 1 3
# [2,] 2 4
example_cast_eigen(x)
# [,1] [,2]
# [1,] 1 3
# [2,] 2 4
example_cast_arma(x)
# [,1] [,2]
# [1,] 1 3
# [2,] 2 4
一个简短的说明:如果您使用的是Eigen的Mapping功能,那么您应该自动在Armadillo矩阵中进行更改(反之亦然),例如
One quick remark: If you are using Eigen's Mapping function, then you should automatically have the change in the Armadillo matrix (and vice versa), e.g.
#include <RcppArmadillo.h>
#include <RcppEigen.h>
// [[Rcpp::depends(RcppEigen)]]
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
void map_update(Eigen::MatrixXd eigen_A) {
Rcpp::Rcout << "Eigen Matrix on Entry: " << std::endl << eigen_A << std::endl;
arma::mat arma_B = arma::mat(eigen_A.data(), eigen_A.rows(), eigen_A.cols(),
false, false);
arma_B(0, 0) = 10;
arma_B(1, 1) = 20;
Rcpp::Rcout << "Armadill Matrix after modification: " << std::endl << arma_B << std::endl;
Rcpp::Rcout << "Eigen Matrix after modification: " << std::endl << eigen_A << std::endl;
}
运行:
map_update(x)
输出:
Eigen Matrix on Entry:
1 3
2 4
Armadill Matrix after modification:
10.0000 3.0000
2.0000 20.0000
Eigen Matrix after modification:
10 3
2 20
这篇关于将Armadillo矩阵转换为Eigen MatriXd,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!