gpt4 book ai didi

r - 通过整数向量进行矩阵索引

转载 作者:行者123 更新时间:2023-12-04 11:11:59 24 4
gpt4 key购买 nike

我想访问不连续的矩阵元素,然后将子选择传递给(例如)sum() 函数。在下面的示例中,我收到有关无效转换的编译错误。我对 Rcpp 比较陌生,所以我相信答案很简单。也许我缺少某种类型的转换表?

#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::plugins("cpp11")]]

double sumExample() {
// these are the matrix row elements I want to sum (the column in this example will be fixed)
IntegerVector a = {2,4,6};
// create 10x10 matrix filled with random numbers [0,1]
NumericVector v = runif(100);
NumericMatrix x(10, 10, v.begin());
// sum the row elements 2,4,6 from column 0
double result = sum( x(a,0) );
return(result);
}

最佳答案

你很接近。索引仅使用 [] -- 参见 this write up at the Rcpp Gallery -- 你错过了导出标签。主要问题是复合表达式有时对于编译器和模板编程来说太多了。所以如果你把它拆开,它就会起作用。

更正代码

#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::plugins("cpp11")]]

// [[Rcpp::export]]
double sumExample() {
// these are the matrix row elements I want to sum
// (the column in this example will be fixed)
IntegerVector a = {2,4,6};
// create 10x10 matrix filled with random numbers [0,1]
NumericVector v = runif(100);
NumericMatrix x(10, 10, v.begin());
// sum the row elements 2,4,6 from column 0
NumericVector z1 = x.column(0);
NumericVector z2 = z1[a];
double result = sum( z2 );
return(result);
}

/*** R
sumExample()
*/

演示

 R> Rcpp::sourceCpp("~/git/stackoverflow/56739765/question.cpp")

R> sumExample()
[1] 0.758416
R>

关于r - 通过整数向量进行矩阵索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56739765/

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