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

标签 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中使用它。
下一次更新:
我想我正在解决这个问题,所以谢谢评论者。这就是我的想法。我需要一个 vector ,该 vector 存储要保留在子矩阵中的索引。我计划使用Rcpp的X.submat()函数。
假设我想获得Sig的子矩阵,该子矩阵不包含第ith行和第ith列。然后,我必须有一个包含{0,1,...,(i-2),i,...,(L-1)}的索引 vector ,因为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++){                     }

最佳答案

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

关于c++ - 有没有一种方法可以排除C++数组中的行和列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63608712/

相关文章:

c++ - 什么是 __SGI_STL_PORT?

python - 查找具有零值的行索引

c - 字符指针数组的段错误

c++ - 表示 native 有符号和无符号整数大小的数据类型?

c++ - std::shared_ptr use_count() 值

c++ - 文本冒险 - 如何在不预先定义每个项目的情况下将项目添加到 'inventory' 结构/类?

C++0X memory_order 无围栏,应用,支持的芯片

c++ - "invalid use of incomplete type"作为模板参数的 const 函数指针类型

arrays - 如何在 Swift 4 中选择要反序列化的 JSON 数组

c++ - 模板依赖 false