Rcpp通过引用传递的更新矩阵,并在R中返回更新 [英] Rcpp Update matrix passed by reference and return the update in R

查看:91
本文介绍了Rcpp通过引用传递的更新矩阵,并在R中返回更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我检查了许多有关如何使用Rcpp进行引用传递的示例.例如,我看到非常好.但是我有一个问题.假设我在R中有一个矩阵作为对象,并且想将1添加到条目[1,1].如果矩阵在Cpp中,则看到的示例有效,但是我想在不使用return语句的情况下在R中返回更新.

I checked many examples about how to pass by reference using Rcpp. I see for instance this very great. However I have one question. Suppose that I have a matrix as an object in R and I want to add 1 to the entry [1,1]. The examples i saw work if the matrix is in Cpp but i want to return the update in R without using return statement.

这是我对列表所做的一个示例,并且效果很好

This is an example i did with a list and it works very well

//[[Rcpp::export]]
void test(List& a){
 a(0)=0;
}

我需要类似地处理矩阵.像这样的东西:

I need to do similarely with a matrix. something like :

//[[Rcpp::export]]
 void test(arma::mat& a){
  a(0,0)=0;
 }

第二个不会更新我在R中的矩阵,而是更新列表.

The second does not update my matrix in R but updates the list.

有人可以帮助我吗?

推荐答案

让我们首先重申一下这可能是不好的做法.不要使用void,返回更改的对象-一种更常见的方法.

Let's start by reiterating that this is probably bad practice. Don't use void, return your changed object -- a more common approach.

也就是说,您可以使它以任何一种方式工作.对于RcppArmadillo,请传递(显式)引用.我得到了想要的行为

That said, you can make it work in either way. For RcppArmadillo, pass by (explicit) reference. I get the desired behaviour

> sourceCpp("/tmp/so.cpp")

> M1 <- M2 <- matrix(0, 2, 2)

> bar(M1)

> M1
     [,1] [,2]
[1,]   42    0
[2,]    0    0

> foo(M2)

> M2
     [,1] [,2]
[1,]   42    0
[2,]    0    0
> 

在此简短示例中:

#include <RcppArmadillo.h>

// [[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::export]]
void bar(Rcpp::NumericMatrix M) {
  M(0,0) = 42;
}

// [[Rcpp::export]]
void foo(arma::mat M) {
  M(0,0) = 42;
}

/*** R
M1 <- M2 <- matrix(0, 2, 2)

bar(M1)
M1

foo(M2)
M2
*/

这篇关于Rcpp通过引用传递的更新矩阵,并在R中返回更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆