c++ - (c++, Armadillo ) 替换矩阵中的一部分列 vector

标签 c++ r rcpp armadillo

我正在将 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/

相关文章:

c++ - 跨各种线程的unique_lock

r - 如何覆盖导入中列出的 R 包中的导出函数

c++ - 使用 Rcpp 的包编译失败

r - 合并多个 hclust 对象(或树状图)

Rcpp 函数选择(并返回)子数据帧

c++ - 将 Rcpp::CharacterVector 转换为 std::string

c++ - 没有递增或递减的 for 循环不好吗?

c++ - 如何拥有具有不同类型值的 map ?

c++ - While 和 Do/While 循环意外中断

database - 如何从 HTML 网页运行 R 脚本