4

For example if I have a 4 by 4 matrix. Is there a way to create another matrix (or a view into original matrix, even better), that is only rows 1 and 3 of original matrix.

I only see how to extract a row, or a block, but no what I mentioned above. Here is my code:

#include <iostream>
#include <Eigen/Dense>

using namespace Eigen;

int main()
{
  Matrix4f m = Matrix4f::Random();
  std::cout << "Matrix : " << std::endl;
  std::cout << m << std::endl;

  std::cout << "row" << std::endl;
  std::cout << m.row(1) << std::endl;

  std::cout << "block : " << std::endl;
  std::cout << m.block(1,0,2,4) << std::endl;
  return 0;
}

A potential solution is to pre-multiply my matrix by a matrix of ones and zeros,

 z = ([[ 0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  1.]])

z * m would give me what I want, but is there a better solution.

Edit:

A possible application of what I want to do:

Let's say I have matrices A(m x n) and B(n x k). I want to sample from A and multiply by B, say I take 1/5th of A's rows A'(m/5 X n) * B(n x k) is what I am after. I don't need A' itself, it is that product that I am after.

Akavall
  • 82,592
  • 51
  • 207
  • 251
  • Well to create another matrix with only rows 1 and 3 can't you just *get rows 1 and 3* and *put them in a new 2x4 matrix*? – Jashaszun Aug 15 '14 at 18:19
  • 1
    @Jashaszun, thanks. How efficient would that solution be? – Akavall Aug 15 '14 at 18:24
  • Probably pretty efficient, as you're only using 8 numbers for the two rows (4 numbers per row). – Jashaszun Aug 15 '14 at 18:25
  • 1
    In practice my matrix is much larger, and maybe I'll need to use the solution you suggested, but I also want to make sure that there is no convenient built-in method for something like this exists. – Akavall Aug 15 '14 at 18:28
  • Oh ok. If the matrices are bigger, then I don't know the efficiency. (I've never even used `eigen` before, so I don't really know what I'm talking about here. Sorry!) – Jashaszun Aug 15 '14 at 18:29
  • Probably you can use [Map](http://eigen.tuxfamily.org/dox/classEigen_1_1Map.html) and [Stride](http://eigen.tuxfamily.org/dox/classEigen_1_1Stride.html). Can you give example of the actual operations you want to do with that new matrix. If it just printing, simply using m.row(1) and m.row(3) should be good enough. – iNFINITEi Aug 19 '14 at 08:29
  • @iNFINITEi, Thank You these look promising. I will update my question. – Akavall Aug 22 '14 at 04:57

1 Answers1

0

Eigen's permutation matrix might be what you're looking for:

Randomly permute rows/columns of a matrix with eigen

using Eigen;
Matrix4f m = Matrix4f::Random();

PermutationMatrix<Dynamic,Dynamic> P(4);
perm.indices()[0] = 1;
perm.indices()[1] = 3;

MatrixXf B = (m * P).leftCols(2);
Mr. White
  • 571
  • 5
  • 12
  • Please explain a little more. A link should serve as an aid to an answer rather than be the answer itself. – Ray Jun 18 '17 at 13:40