2014-03-24 11 views
5

我想知道是否有更好的方法來實現我在這裏做的事情。我有一個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

你說得對,因爲代碼創建了一個新的矩陣A並且沒有就地交換行。

或者,您可以將置換表示爲轉置的乘積,然後將A的行與swap_rows一個接一個地交換。這當然不是微不足道的,只有在內存使用受到關注的情況下,或者只需要對幾行進行排列並保留其餘部分的情況下,我纔會使用此路由。否則,由於緩存效率的原因,重建矩陣可能會更快。

對於你的例子,它只是顛倒了行順序,你當然可能想交換最後一行和第一行,然後是最後一位和第二位,等等。