Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eigen use of diagonal matrix

Using Eigen, I have a Matrix3Xd (3 rows, n columns). I would like to get the squared norm of all columns

to be clearer, lets say I have

Matrix3Xd a =
1    3    2    1
2    1    1    4

I would like to get the squared norm of each column

squaredNorms =
5    10    5    17

I wanted to take advantage of matrix computation instead of going through a for loop doing the computation myself.

What I though of was

squaredNorms = (A.transpose() * A).diagonal()

This works, but I am afraid of performance issues: A.transpose() * A will be a nxn matrix (potentially million of elements), when I only need the diagonal.

Is Eigen clever enough to compute only the coefficients I need? What would be the most efficient way to achieve squareNorm computation on each column?

like image 998
Basile Perrenoud Avatar asked Dec 24 '22 04:12

Basile Perrenoud


2 Answers

The case of (A.transpose() * A).diagonal() is explicitly handled by Eigen to enforce lazy evaluation of the product expression nested in a diagonal-view. Therefore, only the n required diagonal coefficients will be computed.

That said, it's simpler to call A.colwise().squaredNorm() as well noted by Eric.

like image 100
ggael Avatar answered Dec 26 '22 16:12

ggael


This will do what you want.

squaredNorms = A.colwise().squaredNorm();

https://eigen.tuxfamily.org/dox/group__QuickRefPage.html

Eigen provides several reduction methods such as: minCoeff() , maxCoeff() , sum() , prod() , trace() *, norm() *, squaredNorm() *, all() , and any() . All reduction operations can be done matrix-wise, column-wise or row-wise .

like image 25
kangshiyin Avatar answered Dec 26 '22 17:12

kangshiyin