C++ 通过索引向量对犰狳矩阵的所有列进行排序的最佳方法
我想知道是否有更好的方法来实现我在这里所做的事情。我有一个arma矩阵,我想根据C++ 通过索引向量对犰狳矩阵的所有列进行排序的最佳方法,c++,armadillo,C++,Armadillo,我想知道是否有更好的方法来实现我在这里所做的事情。我有一个arma矩阵,我想根据uvec向量中存储的索引对它的所有列重新排序。我想我基本上是在复制整个矩阵 #include <armadillo> using namespace arma; int main(){ // get a discrete random matrix // defined umat because eventually want to
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;
}
#包括
使用arma;
int main(){
//得到一个离散的随机矩阵
//定义umat是因为最终想要
//按a的给定列排序。现在不相关。
umat A=randi(4,6,分布参数(0,3));
std::cout您是对的,代码创建了一个新的矩阵a,并且没有就地交换行
或者,您可以将排列表示为换位的产物,然后使用swap_rows
逐个交换a
中的行。这当然不是一件容易实现的事情,我只会在内存使用受到关注或者您只需要排列其中的几行,而其余的行则保持不变的情况下使用这种方法否则,由于缓存效率的原因,重建矩阵可能会更快
对于只颠倒行顺序的示例,您当然可能希望交换最后一行和第一行,然后交换最后一行和第二行,依此类推。您可以在此处找到更为最新的响应: