【问题标题】:replacing matrix of indices with corresponding vector with armadillo用犰狳用对应的向量替换索引矩阵
【发布时间】:2021-09-04 13:02:50
【问题描述】:

我有一个 arma::umat 矩阵,其中包含对应于 arma::vec 向量的索引,该向量包含 1 或 -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};

我想用向量中的对应值替换矩阵中的每个元素,所以输出如下:

A = {{-1,-1,1,1,-1},{-1,1,-1,1,1,1}}

有什么建议吗? 谢谢

【问题讨论】:

  • arma::umat 用于未签名。因此,您必须创建一个不同的矩阵 (arma::mat) 来保存这些值。另外,请记住索引从 0 开始。因此,对于具有 10 个元素的 v 向量,索引必须在闭区间 [0, 9] 内。

标签: c++ armadillo


【解决方案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, 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;
}

此代码打印

result
  -1.0000  -1.0000   1.0000   1.0000  -1.0000
  -1.0000   1.0000  -1.0000   1.0000   1.0000

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多