Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to delete the diagonal elements of a matrix in MATLAB?

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

A =

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

the the output come:

[2 3;
 1 3;
 1 2];

how can i do it simply ( i know a long one but i need it simple)

like image 964
Mohamad Pishdad Avatar asked Jul 29 '12 14:07

Mohamad Pishdad


2 Answers

Here's 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
like image 197
aioobe Avatar answered Nov 01 '22 10:11

aioobe


Notice that there are two possibilities after you eliminate the diagonal of a n by n matirx:

  1. If the aftermath matrix is n by n-1 (like in your question), you can do it by:

    A=A';
    A(1:n+1:n*n)=[];
    A=reshape(A,n-1,n)';
    
  2. If the aftermath matrix is n-1 by n, you can do it like this:

    A(1:n+1:n*n)=[];
    A=reshape(A,n-1,n);
    
like image 20
chaohuang Avatar answered Nov 01 '22 08:11

chaohuang