问题描述
我有一个 arma::umat 矩阵,其中包含对应于包含 1 或 -1 的 arma::vec 向量的索引:
arma::umat A = { {8,9,7,10,6},{5,3,1,2,4}};
arma::vec v = {-1,-1,1};
我想用向量中的相应值替换矩阵中的每个元素,因此输出如下所示:
A = {{-1,-1},{-1,1}}
有什么建议吗? 谢谢
解决方法
将结果保存到 A
不是一种选择,因为 A
包含无符号整数,而您的 v
向量具有双精度值。只需创建一个 arma::mat
来包含结果并为每一行循环以相应地索引 v
。一种方法是使用 .each_row
成员。
#include <armadillo>
int main(int argc,char *argv[]) {
arma::umat A = {{7,8,6,9,5},{4,2,1,3}};
arma::vec v = {-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;
}
此代码打印
result
-1.0000 -1.0000 1.0000 1.0000 -1.0000
-1.0000 1.0000 -1.0000 1.0000 1.0000