Search code examples
rrcpprcpparmadillo

Negative subscripts in matrix indexing


In Rcpp/RcppArmadillo I want to do the following: From an n x n matrix A, I would like to extract a submatrix A[-j, -j] where j is a vector of indices: In R it can go like

A = matrix(1:16, 4, 4)
j = c(2, 3)
A[-j, -j]

Seems that this functionality is not available in Rcpp or RcppArmadillo - sorry if I have overlooked something. One approach in R is

pos = setdiff(1:nrow(A), j)
A[pos, pos]

That will carry over to RcppArmadillo, but it seems akward having to create the vector pos as the complement of j - and I am not sure how to do it efficiently.

Does anyone have an idea for an efficient implementation / or a piece of code to share?


Solution

  • The armadillo docs have the function .shed which takes an argument(s) that "... contains the indices of rows/columns/slices to remove". From my reading to remove both rows and columns will take two calls of .shed().

    Using your example

    // [[Rcpp::depends(RcppArmadillo)]]
    #include <RcppArmadillo.h>
    
    // [[Rcpp::export]]
    arma::mat fun(arma::mat X, arma::uvec row, arma::uvec col) {
      X.shed_cols(col); // remove columns
      X.shed_rows(row); // remove rows
      return(X);
    }
    
    
    /***R
    A = matrix(1:16, 4, 4)
    j = c(2, 3)
    A[-j, -j]
    
    # minus one for zero indexing
    fun(A, j-1, j-1)
    */