gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:45:26 29 4
gpt4 key购买 nike

我将 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”替换为以下任何一个,那么这个玩具示例子矩阵(矩阵(rnorm(3 * 4),nrow = 3,ncol = 4),c(1:2)) 将返回一条错误消息。

  • (uvec)j :错误:Mat::elem():不兼容的矩阵尺寸:2x0 和 2x1

  • j(unsigned int) j : 没有匹配的成员函数来调用 'submat'

    /li>

我该如何处理这个问题?任何评论将不胜感激!

最佳答案

我不得不承认,您并不完全理解您的问题 - 虽然我认为我有替换给定行或列的“除了一个”元素之外的所有元素的想法。

但是你的代码有很多问题。以下代码已简化(因为我替换了整行),但它逐行分配。您可能想要像这样的 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com