#### Sharing memory with a non-contiguous subset of a matrix in Armadillo/C++

Hi is the following possible and if so, any tips on how to do it?

This is a dummy version of what I would like to achieve: Define three matrices A, B, and C with A_xy standard normally distributed and B_xy = A_xy for A_xy > 0 and 0 otherwise. Likewise C_xy = A_xy for A_xy <= 0 and 0 otherwise.

To avoid a copy operation, I’d like to construct B and C such that the non-zero elements share memory with A. Is that even possible?! If I construct B and C in sparse matrix format then I don’t need to worry about the additional zeros which would not share memory, but this might end up slower, depending on the sparsity of B and C…

In the following B and C obviously don’t share memory with A, but should give an idea of what I want to do:

``````arma_rng::set_seed(1);
mat A;
A.randn(4,4);
uvec indB = find(A > 0);
uvec indC = find(A <= 0);

// Copy construction
mat B, C;
B.zeros(4,4);
B.elem(indB) = A.elem(indB);
C.zeros(4,4);
C.elem(indC) = A.elem(indC);

A.print("A");
B.print("B");
C.print("C");
``````

Which gives as output:

``````A
-0.3868  -0.7951   0.1175  -1.5241
-0.0394  -0.0546  -0.8588  -0.4954
0.6868   1.9379  -0.6483   0.9138
-0.2489   1.0010   0.6746  -0.6272
B
0        0   0.1175        0
0        0        0        0
0.6868   1.9379        0   0.9138
0   1.0010   0.6746        0
C
-0.3868  -0.7951        0  -1.5241
-0.0394  -0.0546  -0.8588  -0.4954
0        0  -0.6483        0
-0.2489        0        0  -0.6272

``````

I have in mind something like:

``````// Auxiliary memory construction
mat B2(vec (A.elem(indB)).memptr(), A.n_rows, A.n_cols, false, true);
B2.print("B2");
``````

Which gives

``````B2
6.8682e-01   6.7457e-01  4.6573e-310  4.6573e-310
1.9379e+00   9.1377e-01  6.9257e-310  6.9257e-310
1.0010e+00  4.6573e-310  4.6573e-310  4.6573e-310
1.1752e-01  6.9257e-310  6.9257e-310  6.9257e-310
``````

Not what I want but hopefully you get the idea!

Thanks!

Source: Windows Questions C++