gpt4 book ai didi

c++ - 遍历 arma::mat 并检索元素位置

转载 作者:行者123 更新时间:2023-12-03 07:15:30 26 4
gpt4 key购买 nike

我正在尝试设置 arma::mat 的值元素方面,每个元素的值取决于每个元素的多索引(行、列)。
有没有办法在迭代期间检索元素的当前位置?
基本上,我想做点什么like in the sparse matrix iterator , 其中 it.col()it.row()允许检索当前元素的位置。
为了说明, arma::sp_mat iterator documentation 中给出的示例) 是:

sp_mat X = sprandu<sp_mat>(1000, 2000, 0.1);

sp_mat::const_iterator it = X.begin();
sp_mat::const_iterator it_end = X.end();

for (; it != it_end; ++it) {
cout << "val: " << (*it) << endl;
cout << "row: " << it.row() << endl; // only available for arma::sp_mat, not arma::mat
cout << "col: " << it.col() << endl; // only available for arma::sp_mat, not arma::mat
}
当然,有许多解决方法可以获取 arma::mat 的元素位置。迭代,最直接的可能是:
  • 使用嵌套 for -循环行和列的大小。
  • 使用单个 for循环,并使用矩阵大小,将迭代次数转换为行和列索引。
  • 某种形式的“压缩”迭代,对象包含或计算相应的索引。

  • 然而,这些对我来说似乎相当老套且容易出错,因为它们需要使用矩阵大小,甚至需要手动处理索引。
    我正在寻找一个更清洁(也许是内部优化)的解决方案。 我觉得应该有一种方法可以实现这一目标......
    除了用于 arma::sp_mat 的解决方案,对我来说,其他这样的“好”解决方案将使用 .imbue .for_each 但是有一个仿函数,它不仅接受元素的当前值,还接受它的位置作为附加参数;目前这似乎是不可能的。

    最佳答案

    查看 Armadillo 源代码,row_col_iterator 提供每个元素的行和列索引。这类似于稀疏矩阵迭代器,但不会跳过零。调整您的代码:

    mat X(10,10,fill::randu);

    mat::const_row_col_iterator it = X.begin_row_col();
    mat::const_row_col_iterator it_end = X.end_row_col();

    for (; it != it_end; ++it) {
    cout << "val: " << (*it) << endl;
    cout << "row: " << it.row() << endl;
    cout << "col: " << it.col() << endl;
    }

    关于c++ - 遍历 arma::mat 并检索元素位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64590176/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com