c++ - 按索引 vector 对 Armadillo 矩阵的所有列进行排序的最佳方法

标签 c++ armadillo

我想知道是否有更好的方法来实现我在这里所做的事情。我有一个 arma 矩阵,我想通过存储在 uvec vector 中的索引重新排序它的所有列。我想我基本上是在复制整个矩阵。

#include <armadillo>
using namespace arma;

int main(){

            // get a discrete random matrix
            // defined umat because eventually want to
            // order by a given column OF A. irrelevant now.
    umat A = randi<umat>(4,6,distr_param(0,3));
    std::cout << "A " << std::endl;
    std::cout << A << std::endl;

    // get an index vector with the now row order
    uvec b;
    b << 3 << 2 << 1 << 0;

    std::cout << "sort by b:" << std::endl;
    std::cout << b << std::endl;


    // get all col indices
    uvec cols = linspace<uvec>(0,A.n_cols-1,A.n_cols);

    // order ALL cols of A by b
            // I'm afraid this just makes a copy
    A = A.submat(b, cols );

    std::cout << "reordered A by b" << std::endl;
    std::cout << A << std::endl;


    return 0;

}

最佳答案

您说得对,因为代码创建了一个新矩阵 A 并且没有就地交换行。

或者,您可以将排列表示为换位的乘积,然后用 swap_rows 逐一交换 A 的行。这当然不是微不足道的实现,只有在内存使用受到关注或者您只需要排列几行并将其余行保持原样时,我才会走这条路。否则,由于缓存效率,重建矩阵可能会更快。

对于您的示例,它只是颠倒了行顺序,您当然可能想要交换最后一行和第一行,然后是最后一行和第二行,依此类推。

关于c++ - 按索引 vector 对 Armadillo 矩阵的所有列进行排序的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22619048/

相关文章:

c++ - 允许将右值绑定(bind)到非常量左值引用吗?

c++ - 未找到 openssl/ssl.h 但已使用 Homebrew 软件安装

C++ "call of overloaded function is ambiguous"编程错误

c++ - 为什么 Armadillo 无法学习高斯混合模型并提示 'no existing means' 尽管随机子集播种?

c++ - 带有英特尔 C++ 编译器的 Armadillo 错误

c++ - Armadillo :从稀疏矩阵中获取稀疏行 vector 的非零位置

c++ - 地址 sanitizer :DEADLYSIGNAL

c++ - 如何引用结构变量并使用或不使用指针进行初始化

r - 将列向量乘以 RcppArmadillo 中的数值标量

r - 使用 sourceCpp() 的 Rcpp 和 RcppArmadillo 在 R 中出错