繁体   English   中英

从索引向量中提取子矩阵

[英]Eigen extracting submatrix from vector of indices

我一直在谷歌搜索一段时间,但无法找到这个简单问题的答案。

在matlab中,我可以这样做:

rows = [1 3 5 9];
A = rand(10);
B = A(rows, : );

我如何在本征中做到这一点? 它似乎不可能。 我发现的最接近的是

MatrixXd a(10,10);
a.row(1); 

,但我想获得多行/列。 另一个用户也问过这里的问题: 如何从Eigen中的索引向量中提取(Eigen :: Vector)子向量? ,但我认为必须有一些内置的方法,因为这是一个我认为非常普遍的操作。

谢谢。

虽然在提出这个问题时这是不可能的,但它已被添加到开发分支中!

这非常直截了当:

Eigen::MatrixXf matrix;
Eigen::VectorXi columns;
Eigen::MatrixXf extracted_cols = matrix(Eigen::all, columns);

所以我猜这将是3.3.5 3.4稳定版。 在那之前,开发分支是要走的路。

不幸的是,即使在Eigen 3.3中,仍然没有直接支持。 有一段时间有这个功能请求: http//eigen.tuxfamily.org/bz/show_bug.cgi?id = 329

Gael链接到其中一条评论中的示例实现: http//eigen.tuxfamily.org/dox-devel/TopicCustomizing_NullaryExpr.html#title1

好的,比方说你有一个3x3矩阵:

m = [3   -1   1; 2.5  1.5 6; 4    7   1]

并说你想从m矩阵中提取以下行:

[0 2], // row 0 and row 2

基本上给出以下矩阵:

new_extracted_matrix = [3 -1 1; 4  7 1]  // row 0 and row 2 of matrix m

这里的主要内容是,让我们创建一个具有内容[0 2]的向量v,意味着我们将从矩阵m中提取以下行索引。 这是我做的:

#include <iostream>
#include <Eigen/Dense>
using namespace Eigen;
using namespace std;
int main()
{
  Matrix3f m;
  m(0,0) = 3;
  m(0,1) = -1;
  m(0,2) = 1;  
  m(1,0) = 2.5;
  m(1,1) = m(1,0) + m(0,1);
  m(1,2) = 6;
  m(2,0) = 4;
  m(2,1) = 7;
  m(2,2) = 1;  
  std::cout << "Here is the matrix m:\n" << m << std::endl; // Creating a random 3x3 matrix
  VectorXf v(2);
  v(0) = 0; // Extracting row 0
  v(1) = 2; // Extracting row 2

  MatrixXf r(1,v.size());
  for (int i=0;i<v.size();i++)
  {
      r.col(i) << v(i); // Creating indice vector
  }
  cout << "The extracted row indicies of above matrix: " << endl << r << endl;

  MatrixXf N = MatrixXf::Zero(r.size(),m.cols());
  for (int z=0;z<r.size();z++)
  {
    N.row(z) = m.row(r(z));
  }

  cout << "Extracted rows of given matrix: " << endl << N << endl;
}

这会给我们以下输出:

这是矩阵m:[3 -1 1; 2.5 1.5 6; 4 7 1]

上述矩阵的提取行指标:[0 2]

提取的给定矩阵行:[3 -1 1; 4 7 1]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM