我正在将 Rcpp 与 Armadillo 库一起使用。我的算法有一个 for 循环,我在每一步都更新第 j 列,而没有第 j 个元素。因此,在一个循环之后,输入矩阵将用新值替换所有非对角线元素。为此,我编写了如下 Rcpp 代码。
arma::mat submatrix(
arma::mat A,
arma::uvec rowid){
for(int j = 0; j < A.n_rows; j++){
A.submat(rowid, "j") = randu(A.n_rows - 1);
}
return A;
}
但是,我不确定子矩阵 View 在 for 循环中如何工作。
如果将上面代码中的“j”替换为下面的任何一个,那么这个玩具示例
submatrix(matrix(rnorm(3 * 4), nrow = 3, ncol = 4), c(1:2))
将返回错误消息。
(uvec) j
:error: Mat::elem(): incompatible matrix dimensions: 2x0 and 2x1
j
或(unsigned int) j
:no matching member function for call to 'submat'
我该如何处理这个问题?任何评论将不胜感激!
最佳答案
我必须承认您没有完全理解您的问题 - 尽管我认为我得到了替换给定行或列的“除一个之外的所有”元素的想法。
但是您的代码有很多问题。以下代码经过简化(因为我替换了整行),但它是逐行分配的。你可能想要这样的东西 X.submat( first_row, first_col, last_row, last_col )
,可能分为两 block (分配在对角线上方,然后分配在下方)。 Armadillo 文档中有更多关于索引的内容,Rcpp Gallery 中也有更多内容。
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
arma::mat submatrix(arma::mat A, arma::uvec rowid, int k) {
for (arma::uword j = 0; j < A.n_rows; j++) {
A.row(j) = arma::randu(A.n_rows).t();
}
return A;
}
/*** R
M <- matrix(1:16,4,4)
submatrix(M, 1, 1)
*/
关于c++ - (c++, Armadillo ) 替换矩阵中的一部分列 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57273777/