Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Rcpp中操纵数值矩阵_R_Rcpp - Fatal编程技术网

在Rcpp中操纵数值矩阵

在Rcpp中操纵数值矩阵,r,rcpp,R,Rcpp,我是Rcpp的新手。我已经阅读了所有的Rcpp案例,但我不知道如何操作numerimatrix对象 有没有什么简单的方法来做这样的事情Rcode 我在评论中指出了我的问题。在第一个(//**1)中,我必须编写两个循环来设置第一行和第一列。 我想问的是:有没有更简单的方法可以做到这一点,就像我们在R中可以做到的那样 这与我在代码注释中指出的问题相同。技术上是的,尽管它只是一个sugar IIRC。 下面是一个简短的演示: library(inline) src <- ' Rcp

我是Rcpp的新手。我已经阅读了所有的Rcpp案例,但我不知道如何操作
numerimatrix
对象

有没有什么简单的方法来做这样的事情
R
code

我在评论中指出了我的问题。在第一个(//**1)中,我必须编写两个循环来设置第一行和第一列。 我想问的是:有没有更简单的方法可以做到这一点,就像我们在R中可以做到的那样


这与我在代码注释中指出的问题相同。

技术上是的,尽管它只是一个sugar IIRC。 下面是一个简短的演示:

library(inline)
src <- '
       Rcpp::NumericMatrix Am(A);
       NumericVector na_vec(Am.ncol(), NA_REAL);      
       Am(0, _) = na_vec;
       Am(_, 0) = na_vec;
       return Am;
'
f <- cxxfunction(signature(A = "numeric"), body = src, plugin = "Rcpp")
f(matrix(1, 3, 3))
#     [,1] [,2] [,3]
#[1,]   NA   NA   NA
#[2,]   NA    1    1
#[3,]   NA    1    1
库(内联)

src你真的读过所有Rcpp的小插曲吗?因为我很确定,封面是你的问题中提到的所有内容。你必须读得非常快,表面上很浅,否则你可能会注意到,方括号索引只因为一个参数而工作,因为C的代码的语义,运算符。我注意到,我的问题中的例子是R,而不是C++。我应该更精确一些。如果没有,是否有任何方法可以修改整个列或子矩阵而不使用:
for(int i=0;i@throwic你试过什么?如果没有这个,你怎么能发现你的实现中的缺陷呢?占卜不是一种常见的技能。要增加得到答案的可能性,在你的帖子中问一个特定的问题(不是在评论中)引用您到目前为止所尝试的内容。非常感谢,这正是我所需要的。我只是想确定一下,我是否错过了Rcpp快速参考指南或小插曲中的答案?我应该在哪里找到它?@throwic不客气!不确定该博士,但我借用了这个德克的答案:
#include <Rcpp.h>
using namespace Rcpp;    

// [[Rcpp::export]]
NumericMatrix lissage_incapC(NumericMatrix mat) {
// INIT
  NumericMatrix x(mat.nrow()+1,mat.ncol()+1);
  NumericMatrix out(mat.nrow(),mat.ncol());

  // Here i want to set x first row and first column to NA_REAL //**1
  for(int i=0; i<x.nrow(); i++){
    for(int j=0; j<x.ncol(); j++){
      if(i==0 || j==0)
        x(i,j) = NA_REAL; 
      x(i,j) = mat(i-1,j-1);
    }
  }


  for(int i=8; i<x.nrow()-1; i++){
    for(int j=1; j<x.ncol()-1; j++){
      NumericMatrix y = x(Range(i-1,i+1),Range(j-1,j+1)); 
      y(1,1) = NA_REAL; 

      if((i == 8) & (j>1))
        y.row(0) = NumericVector::get_na(); //problem here

      out(i,j-1) = 1/2*x(i,j) + 1/2 * mean(na_omit(y));

      }
    }
  out(_,out.ncol()) = 0.5; // Problem here
  out(Range(0,7),_) = out(8,_); // Problem here
  return out;
}
library(inline)
src <- '
       Rcpp::NumericMatrix Am(A);
       NumericVector na_vec(Am.ncol(), NA_REAL);      
       Am(0, _) = na_vec;
       Am(_, 0) = na_vec;
       return Am;
'
f <- cxxfunction(signature(A = "numeric"), body = src, plugin = "Rcpp")
f(matrix(1, 3, 3))
#     [,1] [,2] [,3]
#[1,]   NA   NA   NA
#[2,]   NA    1    1
#[3,]   NA    1    1