Question #6810   Submitted by Answiki on 09/29/2022 at 07:16:55 PM UTC

In Matlab, how to replace the diagonal elements of a matrix with zeros?

Answer   Submitted by Answiki on 09/29/2022 at 07:18:03 PM UTC

With MATLAB, the simplest solution to replace the diagonal elements of a square matrix with zeros is to isolate the diagonal elements and to subtract these elements from the original matrix:

B = A - diag(diag(A))

Here is an example :

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

A =

     1     2     3
     4     5     6
     7     8     9

>> B = A - diag(diag(A))

B =

     0     2     3
     4     0     6
     7     8     0

6 events in history
Answer by Answiki on 09/29/2022 at 07:18:03 PM

With MATLAB, the simplest solution to replace the diagonal elements of a square matrix with zeros is to isolate the diagonal elements and to subtract these elements from the original matrix:

B = A - diag(diag(A))

Here is an example :

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

A =

     1     2     3
     4     5     6
     7     8     9

>> B = A - diag(diag(A))

B =

     0     2     3
     4     0     6
     7     8     0

Question by Answiki 09/29/2022 at 07:17:21 PM
In Matlab, how to put zeros in the diagonal of a square matrix?
Question by Answiki 09/29/2022 at 07:17:16 PM
In Matlab, how to put zeros in the diagonal of a matrix?
Question by Answiki 09/29/2022 at 07:16:55 PM
In Matlab, how to replace the diagonal elements of a matrix with zeros?
Answer by Answiki on 09/29/2022 at 07:16:43 PM

With MATLAB, the simplest solution to replace the diagonal elements of a matrix with 0 is to isolate the diagonal elements and to substract these elements to the original matrix:

B = A - diag(diag(A))

Here is an example :

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

A =

     1     2     3
     4     5     6
     7     8     9

>> B = A - diag(diag(A))

B =

     0     2     3
     4     0     6
     7     8     0

Question by Answiki 09/29/2022 at 07:13:33 PM
In Matlab, how to replace the diagonal elements of a matrix with 0?
# ID Query URL Count

Icons proudly provided by Friconix.