gpt4 book ai didi

c++ - 在 R 中通过引用调用将 C 数组指针转换为 Rcpp

转载 作者:可可西里 更新时间:2023-11-01 16:23:59 27 4
gpt4 key购买 nike

我在 C 中有以下代码。我是 Rcpp 的新手,我想将我必须的 C 代码转换为 Rcpp。

C 代码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>


void calculate(const double *d, double *w, int col, int x) {
int i,j;
for (i = 0; i < col; i++){
for (j = 0; j < x; j++){
w[j * col + i]++;
}
}
}

int main(){

int i, col = 2, row = 6;
int x = 5, y = 3, a = 0;
double d[] = {1.0, 0.8, 0.2, 1.0, 0.4, 0.6, 0.6, 0.4, 0.8, 1.0, 1.0, 0.2};
double *w = (double*)calloc((row - a) * col * x, sizeof(double));


for (i = 0; i < row - a; i++) {
calculate(d + (i + a) * col, w + i * col * x, col, x);
}

}

Rcpp代码:

NumericVector calculate(NumericVector d, NumericVector w, int col, int x) {
int i,j;
for (i = 0; i < col; i++){
for (j = 0; j < x; j++){
w[j * col + i]++;
}
}
return w;
}

int i, col = 2, row = 6;
int x = 5, y = 3, a = 0;
NumericVector w((row - a) * col * x);

for (i = 0; i < row - a; i++) {
w = calculate(d + (i + a) * col, w + i * col * x, col, x);
}

这是我的转换似乎不起作用。我的问题是如何将这些参数 d + (i + a) * colw + i * col * x 作为 Rcpp 中的指针传递,因为它不是索引?

最佳答案

如果您的代码中的以下行按预期工作,

NumericVector w((row - a) * col * x);

为什么不在您的 for 循环中做同样的事情?

for (i = 0; i < row - a; i++) {
NumericVector nvx(d + (i + a) * col);
NumericVector nvy(w + i * col * x);
w = calculate(nvx, nvy, col, x);
}

关于c++ - 在 R 中通过引用调用将 C 数组指针转换为 Rcpp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28836041/

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