假设在C++中有一个数组,如下所示:
1 2 3 4 = arr
5 6 7 8
9 9 8 9
7 6 1 3是否有一种简明的方法来排除任何行和/或列?
例如,假设我想对以下数组执行操作:
1 3 4
5 7 8
7 1 3在其他编程语言中,使用arr-3、-2可以很容易地获得上述数组,以排除第三行和第二列。但是,我无法找到一种简洁的方法来排除C++中的行和列。你会怎么做?
更新:
我想这是一个XY问题。我来告诉你我为什么要这么做。
我正在运行一个统计模型,特别是条件自回归(CAR)模型。在这个高斯模型中,我们需要均值函数和协方差矩阵。
我们得到的平均函数是
平均值= mu + Sig(i,-i) * inv(Sig(-i,-i)) * (v(i,-i) - mu)
而协方差矩阵为
s2 = Sig(i,i) - Sig(i,-i) * inv(Sig(-i,-i)) * Sig(-i,i)
因此,我需要得到矩阵Sig的三个变体: Sig(l,-l),Sig(-l,-l),Sig(-l,l)。这就是为什么我希望找到一种简单的方法来排除行和列。我通常会用R来编程,但是时间太长了。所以,我希望它能在Rcpp中发挥作用。
下一步更新:
我想我已经搞清楚了,谢谢大家的好评。我就是这么想的。我需要一个向量来存储我想要保存在我的子矩阵中的索引。我计划使用Rcpp的X.submat()函数。
假设i想获得不包括ith行和ith列的Sig的子矩阵。然后我必须有一个包含{ 0 ,1,.,(i-2),i,.,(L-1)}的索引向量,因为C++索引从0开始。要获得这个索引向量,我有以下代码:
// We need to get the vector of indices excluding i
arma::vec vece = arma::zeros(L-1); // vector to exclude the ith index
for(int k = 0; k < (L-1); k++){ // we have a vector of length L-1
if(k < (i-1)){
vece(k)=k;
}
else if(k == (i-1)){
// do not add the ith index
}
else{ // k > (i-1)
vece(k-1) = k;
}
}
// We need to make Sig(-i,-i)
arma::mat Sigee = arma::zeros(L-1,L-1); // ee for exclude,exclude
Sigee = Sig.submat(vece,vece)但是,当i=0时,这似乎不起作用。我在下面的for-循环中有这段代码,所以我需要它在i=0时工作。
for(int l = 0; l < L; l++){ }发布于 2020-08-28 11:59:46
在我看来,一种更简单的方法是用顺序整数填充n-1长度uvec,跳过i,如下所示:
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
// [[Rcpp::export]]
arma::mat exclude_one_row_and_col(const arma::mat& X, arma::uword i) {
arma::uword n = X.n_rows; // X should be square so only need # rows
arma::uvec idx(n-1); // vector of indices to subset by
arma::uword ii = 0; // the integer we'll add at each elem of idx
for ( arma::uword j = 0; j < (n-1); ++j ) { // for each elem of idx
if ( ii == i ) { // if ii equals i, we need to skip i
ii += 1; // (i.e., add 1 to ii)
}
idx[j] = ii; // then we store ii for this elem
ii += 1; // and increment ii
}
return X.submat(idx, idx); // finally we can subset the matrix
}一个简单的演示显示了这一功能与预期的一样:
X <- diag(1:3)
X
# [,1] [,2] [,3]
# [1,] 1 0 0
# [2,] 0 2 0
# [3,] 0 0 3
exclude_one_row_and_col(X, 0)
# [,1] [,2]
# [1,] 2 0
# [2,] 0 3
exclude_one_row_and_col(X, 1)
# [,1] [,2]
# [1,] 1 0
# [2,] 0 3
exclude_one_row_and_col(X, 2)
# [,1] [,2]
# [1,] 1 0
# [2,] 0 2https://stackoverflow.com/questions/63608712
复制相似问题