用索引向量对犰狳矩阵的所有列进行排序的最佳方法

时间:2014-03-24 19:39:55

标签: c++ armadillo

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

#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;

}

1 个答案:

答案 0 :(得分:1)

你是对的,因为代码会创建一个新的矩阵A并且不会在适当的位置交换行。

或者,您可以将置换表示为换位的乘积,然后将A的行与swap_rows逐行交换。这当然不是一件容易实现的事情,如果内存使用受到关注,或者你只需​​要对一些行进行置换并将其余部分保留原样,我只会采用这种方式。否则,由于缓存效率,重建矩阵可能会更快。

对于你的示例情况,它只是反转行顺序,你当然可能想要交换最后一行和第一行,然后是最后一行和第二行,依此类推。

相关问题