In my implementations I work a lot with submatrices and blocks of matrices. I am wondering if there is a way in Armadillo that would allow me to extract a block of a larger matrix and use the same memory for this submatrix as for the block within the original matrix. My problem is that I do not know how to go about this as the positions in the original matrix are not contiguous.
Here is one simple example that illustrates what I want to do when my original matrix is A = [A1 A2]
:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
arma::mat foo(arma::mat A, arma::uword block_start, arma::uword block_length) {
arma::uword rows = A.n_rows;
arma::mat B = arma::mat(A.begin_col(block_start), rows, block_length, false);
// fill B here for illustration;
// in the real piece of code I do various manipulations, multiplications, etc using B
B.fill(1.0);
return A;
}
/*** R
A <- matrix(0, 4, 4)
foo(A, 0, 2)
> A <- matrix(0, 4, 4)
> foo(A, 0, 2)
[,1] [,2] [,3] [,4]
[1,] 1 1 0 0
[2,] 1 1 0 0
[3,] 1 1 0 0
[4,] 1 1 0 0
*/
In this case, the positions of the submatrix are contiguous and I can use the advanced constructor to link the memory.
Suppose now that I want the submatrix to be A[1:2, 1:2]
. Can I obtain a copy B
in Armadillo that uses the same memory as the original elements in A
? (Ideally, a solution to this question would also generalize to the case where columns are also non-contiguous, e.g. A[c(1, 3), c(1, 3)]
.)
Edit: To clarify, I really need the matrix B
in the function above to exist on its own. I don't fill
it in my real code, but use it (and multiple other submatrices) in various matrix multiplications etc. So what I'm after is a way to create B
as a non-contiguous submatrix of A
while making sure that they use the same memory.