我正在尝试实现以下R示例Rcpp:
X <- matrix(0, 5, 10)
X[1:4, 4] <- rexp(4)
Run Code Online (Sandbox Code Playgroud)
到目前为止,我尝试过的是:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericMatrix foo1() {
NumericMatrix X(5, 10);
NumericMatrix y(4, 1);
y(_, 0) = rexp(4, 1);
X(Range(0,3),Range(3,3)) = y;
return X;
}
Run Code Online (Sandbox Code Playgroud)
但是我一直收到编译错误,这样说no match for 'operator='。任何暗示我在做什么错将不胜感激。
无论好坏,都缺少使用Rcpp进行矩阵运算的功能。任何深度矩阵工作都应使用RcppArmadillo或RcppEigen完成。
示例实施:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
arma::mat matrix_fill_single_col() {
// Setup X matrix
arma::mat X = arma::zeros<arma::mat>(5, 10);
// Generate random values from exponential and save into a vector.
arma::vec y = Rcpp::as<arma::vec>(Rcpp::rexp(4, 1));
// Fill the fourth column in X (Recall: C++ indexes start at 0 not 1)
X.submat(0, 3, 3, 3) = y;
// Or...
// X.col(3) = y;
return X;
}
Run Code Online (Sandbox Code Playgroud)
测试
matrix_fill_single_col()
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,] 0 0 0 0.2685970 0 0 0 0 0 0
# [2,] 0 0 0 1.6018346 0 0 0 0 0 0
# [3,] 0 0 0 0.6467853 0 0 0 0 0 0
# [4,] 0 0 0 0.6655340 0 0 0 0 0 0
# [5,] 0 0 0 0.0000000 0 0 0 0 0 0
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
95 次 |
| 最近记录: |