# Diagonals of a Matrix

**URL:** <https://openturns.discourse.group/t/diagonals-of-a-matrix/105>\
**Category:** Python usage\
**Created:** [March 17, 2021, 5:56pm UTC](https://openturns.discourse.group/t/diagonals-of-a-matrix/105 "2021-03-17T17:56:52Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![MichaelBaudin](https://yyz2.discourse-cdn.com/free1/user_avatar/openturns.discourse.group/michaelbaudin/32/9_2.png) [@MichaelBaudin](https://openturns.discourse.group/u/MichaelBaudin)\
**Post date:** [March 17, 2021, 5:56pm UTC](https://openturns.discourse.group/t/diagonals-of-a-matrix/105/1 "2021-03-17T17:56:52Z")

</div>

Hi!

Working with @JPelamatti and @vchabri on the development of a new feature for HSIC indices, we have a small issue at porting some code from numpy matrices to OpenTURNS matrices.  
The following code removes the diagonal of the covariance matrix:

```auto
import numpy as np
covarianceMatrix = covarianceModel.discretize(sample)
covarianceMatrix = covarianceMatrix - np.diag(np.diag(covarianceMatrix))

```

What we would need is:

```auto
# Use case 1
A = ot.Matrix([[1 2 3], [4 5 6]])
d = A.getDiagonal() # d = [1 5] > Point

# Use case 2
d = ot.Point([1.0, 5.0])
A = ot.IdentityMatrix(2)
A.setDiagonal(d) # fill_diagonal in numpy

# Use case 3
A = ot.Matrix([[1 2 3], [4 5 6], [7, 8, 9]])
d = ot.Point(3)
A.setDiagonal(d)

# Use case 4
A = ot.Matrix([[1 2 3], [4 5 6], [7, 8, 9]])
d = A.getDiagonal() # d = [1 5, 9] > Point
D = ot.DiagonalMatrix(d)
A -= D

```

But these methods do not exist.  
Do you agree that these would be useful / necessary?  
Regards,  
Michaël

---

<div class="post-metadata">

**Author:** ![josephmure](https://yyz2.discourse-cdn.com/free1/user_avatar/openturns.discourse.group/josephmure/32/114_2.png) [@josephmure](https://openturns.discourse.group/u/josephmure)\
**Post date:** [March 18, 2021, 6:20pm UTC](https://openturns.discourse.group/t/diagonals-of-a-matrix/105/2 "2021-03-18T18:20:26Z")

</div>

Sure, why not? You can tell it would be useful in some places of the C++ code:

> <https://github.com/openturns/openturns/blob/8860b2f14fa3119b013f666e7ff0291cea0d26bc/lib/src/Base/Algo/LeastSquaresMethodImplementation.cxx#L155>

If @JPelamatti wants to try his hand at C++ programming, this could be a good exercise.
