有没有一种方法可以排除C ++数组中的行和列?

时间:2020-08-27 03:25:49

标签: c++ arrays c++11 rcpp

假设我在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(-1,-l),Sig(-l,l)。这就是为什么我希望找到一种简单的方法来排除行和列。我通常会在R中对此进行编程,但是这花费了很长时间。因此,我希望可以在Rcpp中使用它。

下一次更新:

我想我正在解决这个问题,所以谢谢评论者。这就是我的想法。我需要一个向量,该向量存储要保留在子矩阵中的索引。我计划使用Rcpp的X.submat()函数。

假设我要获得Sig的子矩阵,该子矩阵不包含第ith行和第ith列。然后,我必须有一个包含{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++){                     }

1 个答案:

答案 0 :(得分:1)

对我来说,似乎更简单的方法是用连续的整数填充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    2