gpt4 book ai didi

c++ - 使用其他 vector 中的相应元素更改 arma::vec 中给定位置的元素

转载 作者:行者123 更新时间:2023-11-28 02:03:14 25 4
gpt4 key购买 nike

我想知道 Rcpp 中最紧凑的语法是什么,用于更改 vector v1 中位置 pos 处的给定(非连续)元素另一个 vector 中的相应元素(如果我使用的是 arma::vec 类)?说说我会用 R 做什么

v1 = 1:10
pos = c(2,4,10)
v2 = c(3,8,2)
v1[pos] = v2

如果不执行显式 for 循环,这可能吗?

如果这是一个微不足道的问题,我们深表歉意...

最佳答案

我要回答这个问题,即使它确实已经在 Rcpp Gallery: RcppArmadillo Subsetting 中得到了回答。邮政。

子集操作

在 Armadillo 中,API 有 submatrix views使此操作能够发生。

#include <RcppArmadillo.h>
using namespace Rcpp;

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

// [[Rcpp::export]]
arma::vec so_subset_params(arma::vec x, arma::uvec pos, arma::vec vals) {
// Subset and set equal to
x.elem(pos) = vals;
return x;
}

/*** R
v1 = 1:10
pos = c(2,4,10)
v2 = c(3,8,2)
so_subset_params(v1, pos-1, v2)
*/

这会给出:

      [,1]
[1,] 1
[2,] 3
[3,] 3
[4,] 8
[5,] 5
[6,] 6
[7,] 7
[8,] 8
[9,] 9
[10,] 2

在 Armadillo 中复制 R 代码

要在 Armadillo 中 100% 复制您的示例,请使用:

// [[Rcpp::export]]
void so_subset() {

// --------------- 1:10
arma::vec v1 = arma::linspace(1,10,10);

Rcpp::Rcout << "Initial values of V1:" << std::endl << v1 << std::endl;

// --------------- pos=c(2,4,10)

// One style to create a subset index
arma::uvec pos(3);
pos(0) = 2; pos(1) = 4; pos(2) = 10;

Rcpp::Rcout << "R indices pos:" << std::endl << pos << std::endl;


// Adjust for index shift R: [1] => Cpp: [0]
pos = pos - 1;

Rcpp::Rcout << "Cpp indices pos:" << std::endl << pos << std::endl;


// --------------- v2 = c(3,8,2)

// C++98
arma::vec v2;
v2 << 3 << 8 << 2 << arma::endr;

// C++11
// arma::vec v2 = { 3, 8, 2}; // requires C++11 plugin

Rcpp::Rcout << "Replacement values v2:" << std::endl << v2 << std::endl;

// --------------- v1[pos] = v2

// Subset and set equal to
v1.elem(pos) = v2;

Rcpp::Rcout << "Updated values of v1:" << std::endl << v1 << std::endl;
}

/*** R
so_subset()
*/

因此,您将获得与每个操作相关的以下输出。

Initial values of V1:
1.0000
2.0000
3.0000
4.0000
5.0000
6.0000
7.0000
8.0000
9.0000
10.0000

R indices pos:
2
4
10

Cpp indices pos:
1
3
9

Replacement values v2:
3.0000
8.0000
2.0000

Updated values of v1:
1.0000
3.0000
3.0000
8.0000
5.0000
6.0000
7.0000
8.0000
9.0000
2.0000

关于c++ - 使用其他 vector 中的相应元素更改 arma::vec 中给定位置的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38541787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com