Reputation: 621
I have an arma::umat matrix containing indices corresponding to an arma::vec vector containing either 1 or -1:
arma::umat A = { {8,9,7,10,6}, {5,3,1,2,4}};
arma::vec v = {-1, 1, 1, 1, -1, -1, 1, -1, -1 ,1};
I would like to replace each element in the matrix with the corresponding value in the vector, so the output look like this:
A = {{-1,-1,1,1,-1},{-1,1,-1,1,1,1}}
Any suggestions? Thanks
Upvotes: 0
Views: 428
Reputation: 3493
Saving the result into A
is not an option, since A
contains unsigned integers, and your v
vector has doubles. Just create an arma::mat
to contain the result and loop for each row to index v
accordingly. One way to do this is using .each_row
member.
#include <armadillo>
int main(int argc, char *argv[]) {
arma::umat A = {{7, 8, 6, 9, 5}, {4, 2, 0, 1, 3}};
arma::vec v = {-1, 1, 1, 1, -1, -1, 1, -1, -1, 1};
arma::mat result(A.n_rows, A.n_cols);
auto lineIdx = 0u;
// We capture everything by reference and increase the line index after usage.
// The `.st()` is necessary because the result of indexing `v` is
// a "column vector" and we need a "row vector".
A.each_row([&](auto row) { result.row(lineIdx++) = v(row).st(); });
result.print("result");
return 0;
}
This code prints
result
-1.0000 -1.0000 1.0000 1.0000 -1.0000
-1.0000 1.0000 -1.0000 1.0000 1.0000
Upvotes: 1