How to remove diagonal matrix elements in MATLAB?

I need code to omit the diagonal elements of a matrix, for example, if

A =

[1 2 3;
 1 2 3;
 1 2 3];

output:

[2 3;
 1 3;
 1 2];

how can I do this simply (I know a long one, but I just need it)

+5
source share
3 answers

Here is one solution:

Alower = tril(A, -1);
Aupper = triu(A,  1);
result = Alower(:, 1:end-1) + Aupper(:, 2:end)

Demo:

> A = [1 2 3; 1 2 3; 1 2 3]
A =

   1   2   3
   1   2   3
   1   2   3

> tril(A, -1)(1:end, 1:end-1) + triu(A, 1)(1:end, 2:end)
ans =

   2   3
   1   3
   1   2
+5
source

Please note that after eliminating the diagonal non nmatirx there are two possibilities:

  • If the Aftermath matrix is non n-1(as in your question), you can do this:

    A=A';
    A(1:n+1:n*n)=[];
    A=reshape(A,n-1,n)';
    
  • If the Aftermath matrix is n-1on n, you can do it like this:

    A(1:n+1:n*n)=[];
    A=reshape(A,n-1,n);
    
+3
source

Here is another way

reshape(A(setdiff(1:9,1:4:9)),[3,2])
0
source

All Articles