Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify Eigen matrix diagonal

I have an Eigen::MatrixXd and I need to modify the value of the elements in its diagonal. In particular I have another Eigen::MatrixXd with one single column and the same number of rows of the first matrix.

I need to subtract to the diagonal of the first matrix the value of the elements of the second matrix.

Example:

A
 1 2 3
 4 5 6
 7 8 9

B
 1
 1
 1


A'
 0 2 3
 4 4 6
 7 8 8

How can I do?

like image 897
Nick Avatar asked Nov 20 '15 19:11

Nick


2 Answers

This works for me:

A_2=A-B.asDiagonal();
like image 185
Ash Avatar answered Sep 19 '22 10:09

Ash


The simplest and fastest way to do achieve this is:

Eigen::MatrixXd A1(3,3), B(3,1), A2;
...
A2 = A1;
A2.diagonal() -= B;

of course, better use the VectorXd type for vectors (here for B), and finally if B is constant, then you can use array facilities:

A2.diagonal().array() -= 1;
like image 27
ggael Avatar answered Sep 19 '22 10:09

ggael