[英]Passing R matrix to a low-level .C function, accessing the array to change its values
我正在探索基本的.C
調用 - 對於C標准體驗 - 將R矩陣傳遞給C函數,將其用作(bi-dims)C數組。 處理(1-dim)向量我沒有任何問題,但在這種情況下,我收到了一個核心轉儲。 如何訪問數組的每個單元格並更改其值? 這是正確的方法嗎?
我的R矩陣:
> x <- matrix((1:100), ncol=10, nrow=10)
> x
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 23 33 43 53 63 73 83 93
[4,] 4 14 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
[6,] 6 16 26 36 46 56 66 76 86 96
[7,] 7 17 27 37 47 57 67 77 87 97
[8,] 8 18 28 38 48 58 68 78 88 98
[9,] 9 19 29 39 49 59 69 79 89 99
[10,] 10 20 30 40 50 60 70 80 90 100
這是R函數:
testr <- function(x) {
d <- as.integer(dim(x))
r <- .C("testc",
d,
x <- as.integer(x))
return(r[[2]])
}
這是相對C函數:
#include <stdio.h>
#include <math.h>
void testc(int *dim, int *x) {
int i, j;
for (j = 0; j < dim[0]; j++) {
for (i = 0; i < dim[1]; i++) {
x[j][i] = pow(x[j][i], 2);
}
}
}
Alexis Laz發表的評論就是: .C()
接口強制將R中的內容轉換為矩陣(實質上是:向量加維度屬性),直到只有沒有維度的向量。
這就是為什么現在推薦使用.Call()
以及使用SEXP
對象的更豐富界面的眾多原因之一。 如果你使用Rcpp,你甚至不需要做任何事情:
R> cppFunction("NumericMatrix doubleMe(NumericMatrix M) { return 2*M; }")
R> doubleMe(matrix(1:9, 3))
[,1] [,2] [,3]
[1,] 2 8 14
[2,] 4 10 16
[3,] 6 12 18
R>
這只是定義了一個Rcpp單線程來獲取矩陣並返回其值的兩倍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.