Mohamad Pishdad
Mohamad Pishdad

Reputation: 107

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)

Upvotes: 5

Views: 3252

Answers (3)

aioobe
aioobe

Reputation: 420991

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

Upvotes: 5

chaohuang
chaohuang

Reputation: 4115

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);
    

Upvotes: 3

High Performance Mark
High Performance Mark

Reputation: 78316

Here's another way

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

Upvotes: 0

Related Questions