Frage

Is there any simple and efficient way to extract the odd/even numbered rows or columns of the below matrix:

int m=999,n = 1000;
MatrixXd mat(m,n);

and extract them into a new matrix?

One possible way is to use an for loop and put the desired rows/ columns into the corresponding rows/columns of the new matrix. But is there any simpler and more efficient way to do so?

War es hilfreich?

Lösung

No more efficient solution, but for the columns, since you have a column-major matrix with an even number of column, you can reshape the data like such that the even/odd columns forms blocks:

MatrixXd even_cols = MatrixXd::Map(mat.data(), 2*999, 500).topRows(999);
MatrixXd odd_cols  = MatrixXd::Map(mat.data(), 2*999, 500).bottomRows(999);

Another more general approach is to play with strides:

MatrixXd even_cols = MatrixXd::Map(mat.data(),     999, 500, OuterStride<>(2*999));
MatrixXd odd_cols  = MatrixXd::Map(mat.data()+999, 999, 500, OuterStride<>(2*999));

This also work for the even/odd rows with a column-major matrix. In this case we need to define an inner stride of 2:

MatrixXd even_rows = MatrixXd::Map(mat.data(),   500, 1000, Strides<Dynamic,2>(999,2));
MatrixXd odd_rows  = MatrixXd::Map(mat.data()+1, 499, 1000, Strides<Dynamic,2>(999,2));
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top