I would like to go back and forth between an arma::mat
of size M x N and an arma::vec
of size MN (which is a column-major linearization of the matrix).
I can easily go from matrix to vector using arma::vectorise
, i.e.
arma::vec vector = arma::vectorise(matrix);
However, I cannot find a simple way to go the other way around. I would like to insert the first M values of the vector in the first column of the matrix, the second M values in the second column and so on. Is there a way to do so efficiently?
Make the memory from the matrix to be shared with the vector using advanced constructors:
mat X(4,5);
vec V(X.memptr(), X.n_elem, false, false);
// changing elements in X or V will affect both
As long as your operations don't cause aliasing or change the size of either X
or V
, the two objects will keep sharing the memory.