Change the diagonal of the matrix matrix

I have Eigen::MatrixXd, and I need to change the value of the elements in its diagonal. In particular, I have another one Eigen::MatrixXdwith one column and the same number of rows in the first matrix.

I need to subtract the value of the elements of the second matrix on the diagonal of the first 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 this?

+4
source share
4 answers

This works for me:

A_2=A-B.asDiagonal();
+5
source

The easiest and fastest way to achieve this:

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

of course, it is better to use a type VectorXdfor vectors (here for B), and finally, if it Bis a constant, you can use the array facilities:

A2.diagonal().array() -= 1;
+3
for(int i = 0; i < matrix1.rows(); ++i)
    matrix1(i, i) -= matrix2(i, 0);

(matrix1.rows()) 2 (matrix2(i, 0)) 1 (matrix1(i, i)).

0

Eigen . , . (Eigen: Matrix Class .

.

#include <iostream>
#include <eigen3/Eigen/Dense>
using Eigen::MatrixXd;
int main()
{
  MatrixXd matA(3,3), matB(3,1);
  matA<<1,2,3,
    4,5,6,
    7,8,9;
  matB<<1,1,1;
  for(int i=0; i<3;i++)
    matA(i,i) -= matB(i);
  std::cout<<matA<<std::endl;
  return 0;
}

Matrix3d ​​ Vector3d .

0

Source: https://habr.com/ru/post/1616795/


All Articles