从3D Rcpp NumericVector索引切片 [英] Indexing slice from 3D Rcpp NumericVector

查看:353
本文介绍了从3D Rcpp NumericVector索引切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于将NumericVector对象视为多维数组的真正简单的Rcpp问题.我找不到明显的答案.如果是这种情况,请提前道歉-我对C ++的经验不足是要怪的...

Hi I have what I think must be a really simple Rcpp question regarding treating NumericVector objects as multidimensional arrays. I can't find an answer to what might be obvious. Apologies up front if this is the case -- my inexperience with C++ is to blame...

如果我使用此处发布的答案(在Rcpp中构建3D阵列)例如

If I use the answer posted here a (Constructing 3D array in Rcpp) as an example

library("Rcpp")

cppFunction(code='
NumericVector arrayC(NumericVector input, IntegerVector dim) { 
  input.attr("dim") = dim;
  return input;
}
')

如何从输入"对象中提取/访问单个切片/行/列?

How do I extract/access an single slice / row / column out of the "intput" object?

即做类似

NumericMatrix X = input(_,_,i) 
// FYI -- I know this doesn't work! Simply trying to convey the point... 

是的,我知道可以使用RcppArmadillo.我有这样的理由,但不必让其他人厌烦.

And yes I know RcppArmadillo could be used. I have my reasons, for doing things this way but no need to bore folks with them.

谢谢.

推荐答案

我所做的一切您引用的先前答案仍然适用:可行,但可能很痛苦,因为您可能需要编写转换器.捐款仍将受到欢迎.

Everything I wrote in the previous answer you cite still holds: doable, but possibly painful as you may need to write converters. Contributions would still be welcome.

对于它的价值,我使用(Rcpp)Armadillo容器存储三维数据,因为它们确实具有切片运算符.请注意,您不能轻易将它们转换为R喜欢的东西,即,我认为我们仍然自动将cube的转换器转换为矩阵列表.

For what it is worth, I use the (Rcpp)Armadillo containers for three-dimensional data as they do have the slicing operators. Note that you can't easily convert them to something R likes ,ie I think we still automated converters for cube to lists of matrices.

对于它的价值,这里有一个简短的循环来自我最近的GitHub项目:

For what it is worth, here is a short loop from a recent GitHub project of mine:

for (unsigned int j=k-1-1; j>0; j--) {
    arma::mat Ppred = AA.slice(j) * P.slice(j) * AA.slice(j).t() + QQ.slice(j);
    arma::mat lhs = (P.slice(j) * AA.slice(j).t());
    arma::mat rhs = Ppred;
    D.slice(j) = arma::solve(rhs.t(), lhs.t()).t();
    M.col(j) = M.col(j) + D.slice(j) * (M.col(j+1) - AA.slice(j) * M.col(j));
    P.slice(j) = P.slice(j) + D.slice(j) * 
                             (P.slice(j+1) - Ppred) * D.slice(j).t();
}

这在左侧和右侧均使用Armadillo切片.得益于RcppArmadillo,这在R中效果很好(对上述问题进行了模运算,因为R没有真正的本机3维结构,所以我们不能轻易地将3维矩阵传递回去.)

This uses Armadillo slicing on both the left and right-hand sides. And this works rather well from R thanks to RcppArmadillo (modulo the aforementioned issue that because a R has no real native 3-d structure, so we can't pass a 3-d matrix back easily).

这篇关于从3D Rcpp NumericVector索引切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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