Lower triangular of matrix in eigen

4.7k views Asked by At

How to use eigen library to compute lower triangular of input matrix without changing columns order?

for example for matrix:

A=[1 2 3;4 5 6 ;7 8 9]

I want the result to be:

1 0 0
4 0 0
7 0 0
1

There are 1 answers

0
Avi Ginsburg On

Your text and your example don't match. I'll go through the three possible ways I understood your question. First, we'll set up the matrix:

Matrix3d mat;
mat << 1, 2, 3, 4, 5, 6, 7, 8, 9;

If you wanted the actual lower triangular matrix, you would use:

std::cout << Matrix3d(mat.triangularView<Lower>()) << "\n\n";

or similar. The result is:

1 0 0
4 5 0
7 8 9

Note the 5,8,9 which are missing from your example. If you just wanted the left-most column, you would use:

std::cout << mat.col(0) << "\n\n";

which gives

1
4
7

If (as the second part of your example shows) you want mat * [1, 0, 0] then you could either do the matrix multiplication (not recommended) or just construct the result:

Matrix3d z = Matrix3d::Zero();
z.col(0) = mat.col(0);

std::cout << z << "\n\n";

which gives the same result as your example:

1 0 0
4 0 0
7 0 0