将 std::vector 转换为 Rcpp 矩阵

编程入门 行业动态 更新时间:2024-10-11 15:24:32
本文介绍了将 std::vector 转换为 Rcpp 矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是一个 Rcpp 转换相关的问题.我想将一个 long std::vector 转换为一个 Rcpp 矩阵对象,但想知道是否有一种简单的转换格式.自然地,您可以遍历每个元素并填充一个空的 Rcpp 矩阵,但这似乎很容易出错,如果有更方便的方法可能是不必要的.

This is an Rcpp conversion related Q. I'm looking to convert a long std::vector into a Rcpp matrix object, but want to know if there is an easy conversion format. Naturally, you could loop over each element and fill an empty Rcpp matrix, but this seems error prone and possibly needless if a more convenient approach is possible.

我问的原因是我想在一些现有的 C++ 代码中使用 OpenMP,但是将元素直接存储在 OpenMP 循环中的 Rcpp 矩阵对象中似乎效果不佳(而加载 std::vector对象并在 OpenMP 循环完成后转换为矩阵似乎是解决问题的好方法).

The reason I'm asking is I would like to utilize OpenMP in some existing C++ code, but storing element in the Rcpp matrix object directly in an OpenMP loop doesn't appear to work well (whereas loading a std::vector object and converting to a matrix after the OpenMP loop is complete seems to be a decent approach to the problem).

任何帮助将不胜感激!

推荐答案

您选择了一个好的方法.在 OpenMP 上下文中,您必须远离单线程 R.所以 std::vector 是好的.

You chose a good approach. In the OpenMP context, you have to stay away from the single-threaded R. So std::vector is good.

是的,我们有从 std::vector 到 Rcpp::NumericVector 和 Rcpp::NumericMatrix(毕竟是只是一个带有维度属性的向量)以及 Rcoo:Integer* 变体,以及通常的 as<> 和 wrap转换器.

And yes, we have constructors from std::vector to Rcpp::NumericVector and Rcpp::NumericMatrix (which is after all just a vector with a dimensions attribute) as well as the Rcoo:Integer* variants, as well as the usual as<> and wrap converters.

Rcpp 单元测试、Rcpp 示例,当然还有 Rcpp Gallery 网站.

There should be plenty of examples in the Rcpp unit tests, the Rcpp examples, and of course on the Rcpp Gallery site.

这是一个过于简单的例子:

Here is an overly simple example:

R> cppFunction('NumericVector phil(int n) { std::vector<double> x(n); + return wrap(x); }') R> phil(4) [1] 0 0 0 0 R>

更多推荐

将 std::vector 转换为 Rcpp 矩阵

本文发布于:2023-11-05 18:20:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561533.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:矩阵   转换为   std   vector   Rcpp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!