Multiple .colptr in Armadillo

67 Views Asked by At

In Armadillo, there is a pointer to a single column by using .colptr( col_number ). So, we can write, for example,

mat X(nrow, ncol);
vec y(X.colptr(0), nrow, false, true);
X.col(0) = y;

Is there a way to do this for multiple columns of the matrix X such as

mat X(nrow, ncol);
mat Y(X.Multiple_colptr(0, 3), nrow, false, true);
    X.cols(0, 3) = Y;
1

There are 1 best solutions below

0
operator On

This can be done directly with colptr. Pointers can be offset: *(pointer + offset) == pointer[offset]. So a simple way to achieve the functionality you want in multiple_colptr would be to offset a simple colptr. Consider this example (and run it yourself):

mat a = mat(2, 2, arma::fill::randn);
vec b = vec(a.colptr(0), a.n_cols * a.n_rows);

All the entries in a will copied to form a 4 element vec in b. You can obtain any number of columns by varying the pointer from a.colptr(0) and the number of elements to copy (Armadillo follows column-major ordering).

To copy part of a matrix into another you could use

mat a = mat(3, 3, arma::fill::randn);
mat b = mat(a.colptr(1), a.n_rows, 2);

Whilst this is possible, there is probably a better way of doing this with Aramdillo functions. The above example does not include bounds checking.